使用EasyExcel实现数据导出以流输出形式并打包为zip包
pom.xml文件导入easyexcel
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.0.5</version>
</dependency>
导出数据的核心代码
@GetMapping("/export")
public void export(ConsumptionDetailQuery query, HttpServletResponse response) {
try {
String exportRedisFlag = "exportRedisFlag";
if(redisTemplate.hasKey(exportRedisFlag)) {
LOGGER.info("导出正在运行,请稍候重试");
errorResponse(response, "导出正在运行,请稍候重试", 501);
return;
}
List<RiskIndexExport> exportList;//用来存储查询到的数据
Sheet sheet1 = new Sheet(1, 0, ExportModel.class);
sheet1.setSheetName("sheet1");
ByteArrayOutputStream out = new ByteArrayOutputStream();
ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
writer.write(exportList, sheet1);
writer.finish();
String fileName = "exportName";
zipOutput(response, out, fileName);
catch (IOException e) {
LOGGER.error("导出时写入数据到文件出错" + e.getMessage(), e);
errorResponse(response, "写入数据到文件出错", 500);
} finally {
redisTemplate.delete(exportRedisFlag);
}
}
zipOutput()方法代码
private void zipOutput(HttpServletResponse response, ByteArrayOutputStream out, String fileName) throws IOException {
ZipOutputStream zipout = null;
InputStream inputStream = null;
try {
response.setContentType("application/force-download");
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment; filename=" + new String((fileName+".zip").getBytes("UTF-8"), "ISO8859-1"));
inputStream = new ByteArrayInputStream(out.toByteArray());
zipout = new ZipOutputStream(response.getOutputStream());
//excel文件写入zip
zipout.putNextEntry(new ZipEntry(fileName+".xlsx"));
int len;
byte[] buf = new byte[1024];
while ((len = inputStream.read(buf)) > 0) {
zipout.write(buf, 0, len);
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
LOGGER.error("zipFiles exception:{}", e.getMessage());
} finally {
if (zipout != null) {
zipout.close();
}
if (inputStream != null) {
inputStream.close();
}
}
}
errorResponse方法代码
private void errorResponse(HttpServletResponse response, String message, Integer code) {
try {
Map map = new HashMap();
map.put("code", code);
map.put("msg", message);
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getOutputStream().write(JSONObject.toJSONString(map).getBytes());
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
ExportModel 实体类(需要继承BaseRowModel)
public class ExportModel extends BaseRowModel {
//注解形式实现标题行
@ExcelProperty(value = "编号", index = 0)
private String id;
@ExcelProperty(value = "指标", index = 1)
private String name;
@ExcelProperty(value = "年龄", index = 2)
private String age;
}