压缩多个excel成一个压缩包,浏览器下载
https://blog.csdn.net/Fannie08/article/details/84252684
https://blog.csdn.net/weixin_33895016/article/details/86022623
首先明白一点;
请求--响应
输入流--输出流。
一个输入流;一个输出流
不可能一个输出流同时多次传输下载多个文件,只能一次传输下载,如果要同时下载多个文件,就采用压缩包的方式一次传输下载。
java.util.zip
核心类:
压缩包的输出流:
ZipOutputStream:
public ZipOutputStream(OutputStream out);
public void putNextEntry(ZipEntry e);
压缩包中一个元素定义:
public ZipEntry(String name);
多个文件就封装多个ZipEntry;
将XSSFWorkbook转成输入流的方法:
public static InputStream workbookToInpustream(XSSFWorkbook workbook) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
byte[] barray = bos.toByteArray();
return new ByteArrayInputStream(barray);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
controller层:
@ResponseBody
@RequestMapping("/exportZipFile")
public void exportZipFile(HttpServletResponse response) throws Exception {
String currTime = "2020-03-25";
response.setContentType("application/octet-stream");
//如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
// 处理方法1 response.setHeader("Content-Disposition", "attachment;filename=" +URLEncoder.encode(file.getName(), "UTF-8"));
//处理方法2
String zipfileName= new String(("报表数据-"+currTime).getBytes(), "iso-8859-1");
response.setHeader("Content-Disposition", "attachment; filename="+zipfileName+".zip");
ZipOutputStream zos = null;
XSSFWorkbook book1;
XSSFWorkbook book2;
book1 = new XSSFWorkbook(new File("D:\\jo1.xlsx"));
book2 = new XSSFWorkbook(new File("D:\\jo2.xlsx"));
List<XSSFWorkbook> workbooks = new ArrayList<>();
workbooks.add(book1);
workbooks.add(book2);
try {
zos = new ZipOutputStream(response.getOutputStream());
//循环把文件流添加到压缩包中
for (int i = 0; i < workbooks.size(); i++) {
XSSFWorkbook workbook = workbooks.get(i);
//获取文件流
InputStream input = workbookToInpustream(workbook);
//压缩文件名称 设置ZipEntry对象
String name="bookname"+i;
zos.putNextEntry(new ZipEntry(name + ".xlsx"));
// 设置注释
zos.setComment("日检查报表");
int temp;
// 读取内容
while ((temp = input.read()) != -1) {
// 压缩输出
zos.write(temp);
}
input.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != zos) {
zos.flush();
zos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}