踩坑记录:生成的多个excel文件,压入压缩包返回

一、代码

public static void exportXlsx2Zip(String fileName, List<Workbook> workbookList, HttpServletResponse response) throws IOException {
        // 1、创建临时zip文件
        String zipPath = "";
        File zipFile = new File(zipPath + fileName + ".zip");
        zipFile.createNewFile();
        FileOutputStream f = new FileOutputStream(zipFile);
        CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
        ZipOutputStream zos = new ZipOutputStream(csum);
        try {
            InputStream is = null;
            Iterator<Workbook> iterator = workbookList.stream().iterator();
            while (iterator.hasNext()) {
                try {
                    Workbook workbook = iterator.next();
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    try {
                        workbook.write(os);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    byte[] content = os.toByteArray();
                    // 1(3)、写入输入流
                    is = new ByteArrayInputStream(content);
                    // 1(4)、压入zip
                    zos.putNextEntry(new ZipEntry(fileName));
                    int bytesRead = 0;
                    while ((bytesRead = is.read()) != -1) {
                        zos.write(bytesRead);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    is.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            zos.closeEntry();
            // 这里不能忘了
            zos.close();
            csum.close();
            f.close();
        }
        // 要在zos.close()后
        response.setContentType("application/zip");
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName + ".zip", "UTF-8"));
        try (FileInputStream inputStream = new FileInputStream(zipFile)) {
            IOUtils.copy(inputStream, response.getOutputStream());
        }
    }

二、问题汇总

1、poi过时方法:

cell.getCellType ();

去官方文档看了下
在这里插入图片描述
在这里插入图片描述
当时是因为该方法返回 int 不安全,所以加了个 getCellTypeEnum() 方法返回了枚举类。然后4.0以上版本修复了这个问题。

2、压缩失败:

打开压缩文件显示:
不可预料的压缩文件末端

1)、ZipOutputStream 没有 close

2)、response 返回,应该在 zipOutputStream.close() 之后

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w_tt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值