文件效果图:

接口代码:
//测试 http://localhost:8080/admin/test/test/poizip
@RequestMapping(value = "/poizip")
public void poizip(HttpServletResponse response) throws IOException {
//response 输出流
ServletOutputStream out = response.getOutputStream();
//压缩输出流
ZipOutputStream zipOutputStream = new ZipOutputStream(out);
try {
for (int i = 0; i < 6; i++) {
//创建工作簿
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("sheet" + i);
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue("内容" + i);
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + Encodes.urlEncode("测试.zip"));
//重点开始,创建压缩文件
ZipEntry z = new ZipEntry(i + ".xls");
zipOutputStream.putNextEntry(z);
//写入一个压缩文件
wb.write(zipOutputStream);
}
zipOutputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
//注意关闭顺序,否则可能文件错误
if (zipOutputStream != null) {
zipOutputStream.close();
}
if (out != null) {
out.close();
}
}
}
本文介绍了一种使用Java技术批量生成多个Excel文件,并将其压缩为一个ZIP文件供用户下载的方法。通过示例代码展示了如何利用HSSFWorkbook创建Excel工作簿,设置单元格内容,以及如何通过ServletOutputStream和ZipOutputStream实现文件的压缩与输出。
964

被折叠的 条评论
为什么被折叠?



