准备根据传的参数,生成excel列的头,决定excel有多少列
@GetMapping(value = "/outExcel")
public Object outExcelDemo(HttpServletResponse response) throws IOException {
//创建HSSFWorkbook对象(excel的文档对象)
Workbook wb = new XSSFWorkbook();
//创建sheet对象(excel的表单)
Sheet sheet = wb.createSheet("User");
sheet.setDefaultColumnWidth(20);
//创建第一行,这里即是表头。行的最小值是0,代表每一行,上限没研究过,可参考官方的文档
Row row1=sheet.createRow(0);
//在这一行创建单元格,并且将这个单元格的内容设为“账号”,下面同理。
//列的最小值标识也是0
row1.createCell(0).setCellValue("名字");
row1.createCell(1).setCellValue("手机号");
row1.createCell(2).setCellValue("密码");
row1.createCell(3).setCellValue("登录标识");
row1.createCell(4).setCellValue("权限");
row1.createCell(5).setCellValue("修改时间");
List<User> list = userMapper.selectList(null);
for (int i = 0; i < list.size(); i++) {
//第二行
Row row2 = sheet.createRow(i + 1);
row2.createCell(0).setCellValue(list.get(i).getEmail());
row2.createCell(1).setCellValue(list.get(i).getId());
row2.createCell(2).setCellValue(list.get(i).getName());
row2.createCell(3).setCellValue(list.get(i).getTime());
if (list.get(i).getAge()==null){
row2.createCell(4).setCellValue("null");
}else {
row2.createCell(4).setCellValue(list.get(i).getAge());
}
if (list.get(i).getAge()==null){
row2.createCell(5).setCellValue("null");
}else {
row2.createCell(5).setCellValue(list.get(i).getCreateTime());
}
}
//输出Excel文件
OutputStream output=response.getOutputStream();
response.reset();
response.setHeader("Content-disposition", "attachment; filename=demo.xlsx");
response.setContentType("application/x-xls");
wb.write(output);
output.close();
return null;
}