POI多个工作簿导出表格打包ZIP下载

时间:2019-10-25
本文章向大家介绍POI多个工作簿导出表格打包ZIP下载,主要包括POI多个工作簿导出表格打包ZIP下载使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

首先获得workbook集合对象

public static void zipFiles(List<XSSFWorkbook> srcfile, File zipfile,String fileName) {
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
for (int i = 0; i < srcfile.size(); i++) {
ZipEntry entry = new ZipEntry(fileName+i+".xls");
out.putNextEntry(entry);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
srcfile.get(i).write(bos);
bos.writeTo(out);
out.closeEntry();
bos.close();
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}

}
将多个workbook工作簿添加到ZipOutputStream中。(特别要注意此处的out.putNextEntry(entry);如果直接使用Workbook的write()方法,会自动关闭传入的参数,导致再次使用putNextEntry()方法是报错Stream closed。所以此处使用了
ByteArrayOutputStream 进行包装)

public static HttpServletResponse downFile(HttpServletResponse response, File file) {
try {
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/x-zip-compressed");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
客户端下载文件
File temp = File.createTempFile("temp",".zip");
ClassController.zipFiles(workbooks,temp,"考勤表");
rep = ClassController.downFile(rep, temp);
temp.deleteOnExit();

原文地址:https://www.cnblogs.com/xiao1993/p/11738694.html