之前做过一个导出多个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(); } }
标签:zipOutputStream,Java,Excel,new,servletOutputStream,response,压缩包 From: https://www.cnblogs.com/ZDY-XJ/p/18080581