背景
业务要求我们批量生成一批excel,并将这些excel压缩成一个压缩包导出给前端。
实现
java自带了ZipOutputStream
,可以直接生成压缩包,因此,我们直接使用这个,在内存中生成压缩包,直接返回给前端。(特别注意,这个方法要注意内存消耗问题,数据量大慎用)
代码如下:
String fileName = "导出结果";String finalFileName = String.format("%s%s", URLEncoder.encode(fileName, StandardCharsets.UTF_8), ".zip");response.setContentType(MediaType.APPLICATION_JSON_VALUE);response.setCharacterEncoding("utf-8");response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename*=utf-8''" + finalFileName);response.setHeader("fileName", finalFileName);try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {for (Long id : condition.getIds()) {// 导出成excel的workbook的代码略过try (Workbook workbook = doExport(id )) {zipOutputStream.putNextEntry(new ZipEntry(id + ".xlsx"));workbook.write(zipOutputStream);zipOutputStream.closeEntry();}}zipOutputStream.finish();} catch (IOException e) {throw new RuntimeException(e.getMessage(), e);}
结束