【Java】批量生成Excel放入文件夹并打zip压缩包
本文展示了Java批量生成并下载Excel报表为ZIP文件的技术实现。
先看一下生成文件的效果示例:
直接上代码:
public void reportDownBatch(HttpServletResponse response) {// 设置响应的内容类型和头信息response.setContentType("application/zip");response.setHeader("Content-Disposition", "attachment; filename=\"" + "report" + "\"");// 获取输出流InputStream input = null;try (OutputStream outputStream = response.getOutputStream();ZipOutputStream zos = new ZipOutputStream(outputStream);) {String fileName;ZipEntry zipEntry;ZipEntry fileEntry;// 这里以月份作为示例,改为实际获取文件夹名称的方法List<String> list = Arrays.asList("2025-01", "2025-02", "2025-03");for (String month : list) {// 创建ZIP中的文件夹,改为实际文件夹名fileName = month + "/";zipEntry = new ZipEntry(fileName);zos.putNextEntry(zipEntry);zos.closeEntry();// 生成文件,改为实际的查询参数及方法input = exportFile(month);// 目录里层文件名(文件夹名+文件名),改为实际文件名fileEntry = new ZipEntry(fileName + month + "-28.xlsx");zos.putNextEntry(fileEntry);byte[] buffer = new byte[1024];int len;while ((len = input.read(buffer)) > 0) {zos.write(buffer, 0, len);}zos.closeEntry();input.close();}} catch (IOException e) {log.error(e.getMessage());e.printStackTrace();} finally {try {if (input != null) {input.close();}} catch (IOException e) {log.error("关闭输入流出错", e);}}}public InputStream exportFile(String month) {// 1.初始化FillConfig fillConfig = FillConfig.builder().build();ByteArrayOutputStream os = new ByteArrayOutputStream();// 2.获取表格模板,下面有模板示例(替换为真实的模板路径)InputStream inputStream = getClass().getResourceAsStream("/static/excelTemplate.xlsx");ExcelWriter excelWriter = EasyExcel.write().withTemplate(inputStream).excelType(ExcelTypeEnum.XLSX).file(os).build();// 3.获取模板第一个sheet页WriteSheet sheet = EasyExcel.writerSheet(0).build();// 4.填充表头参数(不需要的话可以直接删除)Map<String, Object> titleMap = new HashMap<>();titleMap.put("title", "标题");excelWriter.fill(titleMap, sheet);// 5.填充列表数据(替换为实际查询数据的方法)List<Report> reportList = mapper.getListByMonth(month);excelWriter.fill(new FillWrapper("reportList", reportList), fillConfig, sheet);// 如有其他sheet页重复步骤3-5// 6.结束填充excelWriter.finish();InputStream stream = new ByteArrayInputStream(os.toByteArray());return stream;}
excel模板示例:
注意参数名称和代码中一致。