1、构建导出的数据模型,
这个模型可以自己画,也可以读取一个自己制作好的模板,根据模板填充数据,然后flush到一个新的excel文件。
1)、自己画
@GetMapping("/exportTemplate")
public void exportTemplate(HttpServletResponse response) throws IOException {
String column1Name1 = "时间戳";
String column1Name2 = "设备名称";
List<String> headList = new ArrayList<>();
headList.add(column1Name1);
headList.add(column1Name2);
//在内存操作,写到浏览器
ExcelWriter writer= ExcelUtil.getWriter(true);
// 设置表头的宽度
writer.setColumnWidth(0, 20);
writer.addHeaderAlias("timestamp",column1Name1);
writer.setColumnWidth(1, 15);
writer.addHeaderAlias("deviceName",column1Name2);
// 默认的,未添加alias的属性也会写出,如果想只写出加了别名的字段,可以调用此方法排除之
writer.setOnlyAlias(true);
// 表格内容【相比上一节新内容】
List<CollectDataExcelVo> excelList = new ArrayList<>();
CollectDataExcelVo vo1 = new CollectDataExcelVo();
vo1.setDeviceName("A类设备");
vo1.setTimestamp(DateUtil.format(new Date()));
excelList.add(vo1);
CollectDataExcelVo vo2 = new CollectDataExcelVo();
vo2.setDeviceName("B类设备");
vo2.setTimestamp(DateUtil.format(new Date()));
excelList.add(vo2);
writer.writeHeadRow(headList).write(excelList);
//设置content—type
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode("数据集导入模板","UTF-8")+".xlsx");
ServletOutputStream outputStream= response.getOutputStream();
//将Writer刷新到OutPut
writer.flush(outputStream,true);
outputStream.close();
writer.close();
}
------------------------------------------------------------------------------------------------------------------
2、读取自定义的模板,如
public static void responseExport(HttpServletResponse response, Workbook workbook, String fileName) throws IOException { response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx"); response.setContentType("application/force-download"); response.setContentType("application/vnd.ms-excel;charset=UTF-8"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); BufferedOutputStream bufferedOutPut = new BufferedOutputStream(response.getOutputStream()); workbook.write(bufferedOutPut); bufferedOutPut.flush(); bufferedOutPut.close(); }