Java导出多个Excel放在压缩包里
之前做过一个导出多个Excel放在压缩包里的需求,当时也是网上找的思路,现在已经找不到之前的文章了,不多废话直接上代码。
public void export(HttpServletRequest request, HttpServletResponse response) { String zipFileName = "zipname.zip"; List<Workbook> workbooks = new ArrayList<>(); ServletOutputStream servletOutputStream = null; try { servletOutputStream = response.getOutputStream(); try { response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(zipFileName, "UTF-8")); } catch (UnsupportedEncodingException e) { throw new BusinessException("文件名编码异常"); } ZipOutputStream zipOutputStream = new ZipOutputStream(servletOutputStream); // 导出的数据 List<Dto> dtos = new ArrayList<>(); try { for (int i = 0; i < dtos.size(); i++) { Workbook workbook = new XSSFWorkbook(); //向压缩包中添加Excel ZipEntry zipEntry = new ZipEntry("excelname" + "-" + i + ".xlsx"); zipOutputStream.putNextEntry(zipEntry); //向zipOutputStream中写入流数据 workbook.write(zipOutputStream); } zipOutputStream.flush(); } catch (Exception e) { log.error(e.getMessage()); e.printStackTrace(); } finally { if (zipOutputStream!=null){ zipOutputStream.close(); } if (servletOutputStream!=null){ servletOutputStream.close(); } } } catch (Exception e) { e.printStackTrace(); } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步