今天来记录一下导出excel的实现方式,导出的格式是xlsx的文件。
这里用到的是hutool的工具包,依赖如下:
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.3.5</version><scope>compile</scope> </dependency><!--读取excel组件--> <dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version> </dependency>
导出代码如下:
@PostMapping(value = "download", consumes = APPLICATION_JSON_VALUE)public void download(@RequestBody QaLogPageVO pageVO, HttpServletResponse response) throws IOException {List<QaLog> list = service.list();ExcelWriter writer = ExcelUtil.getWriter(true);//自定义标题别名writer.addHeaderAlias("name", "姓名");writer.addHeaderAlias("time", "提问时间");writer.addHeaderAlias("model", "模型");writer.addHeaderAlias("question", "问题");writer.addHeaderAlias("answer", "答案");writer.addHeaderAlias("source", "来源");writer.addHeaderAlias("feedbackStatus", "反馈");writer.addHeaderAlias("department", "部门");// 默认的,未添加alias的属性也会写出,如果想只写出加了别名的字段,可以调用此方法排除之writer.setOnlyAlias(true);String title = DateUtil.format(startTime,"yyyy-MM-dd HH:mm:ss") +"——"+ DateUtil.format(endTime,"yyyy-MM-dd HH:mm:ss");// 合并单元格后的标题行,使用默认标题样式writer.merge(7, title);// 一次性写出内容,使用默认样式,强制输出标题writer.write(list, true);response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");response.setHeader("Content-Disposition", "attachment;filename=test.xlsx");ServletOutputStream out = response.getOutputStream();writer.flush(out, true);writer.close();IoUtil.close(out);}