Java导出多个excel压缩成zip下载
<!--hutoos工具类根据需要可以导入不同的模块,我这里是导入全部的模块-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.8</version>
</dependency>
<!--poi对excel2007以上版本的支持-->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
@SneakyThrows
@GetMapping("downloads1")
public void downloads1(HttpServletResponse response){
String zipFileName = "student.zip";
ServletOutputStream servletOutputStream = response.getOutputStream();
try (ZipOutputStream zipOutputStream = new ZipOutputStream(servletOutputStream)) {
for (int i = 0; i < 2; i++) {
Map<String, Object> row1 = new LinkedHashMap<>();
row1.put("姓名", "张三");
row1.put("年龄", 23);
row1.put("成绩", 88.32);
row1.put("是否合格", true);
row1.put("考试日期", DateUtil.date());
Map<String, Object> row2 = new LinkedHashMap<>();
row2.put("姓名", "李四");
row2.put("年龄", 33);
row2.put("成绩", 59.50);
row2.put("是否合格", false);
row2.put("考试日期", DateUtil.date());
ArrayList<Map<String, Object>> rows = CollUtil.newArrayList(row1, row2);
ExcelWriter writer = ExcelUtil.getWriter();
writer.merge(row1.size() - 1, "一班成绩单" + i);
writer.write(rows);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
writer.flush(byteArrayOutputStream);
zipOutputStream.putNextEntry(new ZipEntry("ExcelName" + i + ".xls"));
zipOutputStream.write(byteArrayOutputStream.toByteArray());
zipOutputStream.flush();
writer.close();
zipOutputStream.closeEntry();
}
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=test.xls");
response.setContentType("text/html; charset=UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(zipFileName, "UTF-8"))));
}
servletOutputStream.close();
}
- 效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/f59b6afb7efa24f8e4944b0641d43aea.png)
- 文件内容
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3dc96de970194378370ff9aeb5d3744c.png)