1、背景
之前的导出都是基于生成本地zip文件,然后往zip文件里放需要压缩的文件的,这样做的弊端就是会留一个本地文件,虽然可以删除,但是心里不舒服。
2、zip文件导出实现
public void declarationPlanExport(HttpServletResponse response) throws IOException {
//创建zip输出流
ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
//将excel文件放入zip压缩包
for (int i = 0; i < 3; i++) {
InputStream fis = declarationPlanFileBuild();
//设置每个压缩文件的文件名称
out.putNextEntry(new ZipEntry("xx文件" + i + ".xlsx"));
int len;
// 读入需要下载的文件的内容,打包到zip文件
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
fis.close();
}
out.close();
OutputStream outs = response.getOutputStream();// 获取文件输出IO流
BufferedOutputStream bouts = new BufferedOutputStream(outs);
response.setContentType("application/x-download");// 设置response内容的类型
response.setHeader(
"Content-disposition",
"attachment;filename="
+ URLEncoder.encode("xxxx.zip", "UTF-8"));// 设置头部信息
bouts.flush();// 这里一定要调用flush()方法
outs.close();
bouts.close();
}
3、文件写入InputStream
private InputStream declarationPlanFileBuild() {
//表数据
List<List<String>> tableData = new ArrayList<>();
for (String p : TimeConstant.TWENTY_FOUR_TIME_FRAMES) {
tableData.add(Arrays.asList(p, "0.1", "0.2", "0.1", "0.2"));
}
tableData.add(Arrays.asList("合计", "2.40", "0.2", "2.4", "0.2"));
//表头
List<List<String>> heads = new ArrayList<>();
List<String> firstHead = new ArrayList<>();
firstHead.add("");
firstHead.add("时间类型");
heads.add(firstHead);
List<CellWriteHandler> cellWriteHandlerList = new ArrayList<>();
int index = 1;
for (String p : Arrays.asList("A企业", "B企业")) {
List<String> cell1 = new ArrayList<>();
List<String> cell2 = new ArrayList<>();
//相同字段合并单元格
cell1.add(p);
cell2.add(p);
cell1.add("量");
cell2.add("价");
heads.add(cell1);
heads.add(cell2);
cellWriteHandlerList.add(new CustomTotalRowMergeStrategy(0, (index * 2) - 1, index * 2));
index++;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
DownloadUtil.downloadDynamicHeadExcel(heads, tableData, cellWriteHandlerList, null, outputStream, null);
//数据流转输入流,暂不知道有没问题,大文件可能有问题,小文件肯定没问题
return new ByteArrayInputStream(outputStream.toByteArray());
}