问题描述:
java批量导出excel,并压缩下载
问题分析:
考虑两种方案:
1.将单个excel下载到指定的磁盘,然后读取压缩下载。
2.在程序中创建多个excel文佳,压缩下载。
最后考虑简洁,快速,采用第二种解决方案。
解决方案:
controller层代码
@RequestMapping(value = "exportExcelZip",method = RequestMethod.GET)
@ResponseBody
public void exportExcelZip(@RequestParam(name = "taskId") String taskId, HttpServletResponse response) {
try {
service.exportExcelZip(taskId,response);
} catch (Exception e) {
e.printStackTrace();
......
}
return;
}
service层代码:
public void batchExportExcel(String taskIds,HttpServletResponse response) {
ZipOutputStream zipOutputStream = null;
OutputStream _fOut = null;
String [] taskIdArray = taskIds.split(",");
try {
// 新建一输出文件流
_fOut = response.getOutputStream();
zipOutputStream = new ZipOutputStream(_fOut);
String fileName = "批量文件下载名称.zip";
response.setContentType("application/octet-stream ");
// 表示不能用浏览器直接打开
response.setHeader("Connection", "close");
// 告诉客户端允许断点续传多线程连接下载
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(fileName.getBytes("GB2312"), "ISO8859-1"));
response.setCharacterEncoding("UTF-8");
if(null != taskIdArray && taskIdArray.length > 0){
for(int n = 0;n < taskIdArray.length;n++){
//这个方法生成单个excel表格文件以及名称
Map maps = exportSimpleExcel(taskIdArray[n]);
ZipEntry zipEntry = new ZipEntry( maps.get("fileName") + "-" + n + ".xls");
zipOutputStream.putNextEntry(zipEntry);
HSSFWorkbook workbook = (HSSFWorkbook)maps.get("workbook");
workbook.write(zipOutputStream);
}
}
// 操作结束,关闭文件
_fOut.close();
logger.info("批量下载成功!");
} catch (Exception e) {
logger.error("批量下载失败" + e.getMessage());
System.out.print(e.getMessage());
}finally {
try {
if (zipOutputStream != null) {
zipOutputStream.flush();
zipOutputStream.close();
}
if (_fOut != null) {
_fOut.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}