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();
    }
}
复制代码

 

posted @   《END》  阅读(307)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示