java 解决 XSSFWorkbook列表压缩zip报错:stream closed 问题

在开发下载多个excel打包zip文件时遇到问题如下:

for (Workbook workbook : workbooks) {
  ZipEntry zipEntry = new ZipEntry("数据导出" + i+ ".xlsx");
                    zipOutputStream.putNextEntry(zipEntry);                 
                    workbook.write(zipOutputStream);
                    zipOutputStream.closeEntry();

}

zipOutputStream.flush();
zipOutputStream.close();

在for循环中使用上述代码,第一个workbook 写入完成后,报错stream closed。

原因为XSSFWorkbook.write 会自动关闭流,导致后续执行时报stream closed。

解决方法如下:

1、创建一个ByteArrayOutputStream,先将workbook写入ByteArrayOutputStream中,然后在写入zipOutputStream,即使在写入ByteArrayOutputStream后将流关闭,也不会影响zipOutputStream。直接上代码:

 

 ZipEntry zipEntry = new ZipEntry("数据导出" + i+ ".xlsx");
 zipOutputStream.putNextEntry(zipEntry); 
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
bos.writeTo(zipOutputStream);

 

2、自己创建类继承ZipOutputStream 对象,并重写close方法。代码中zipOutputStream使用继承类,解决。

 

public class UncloseableZipOutputStream extends ZipOutputStream
{
	OutputStream os;
	
	public UncloseableZipOutputStream( OutputStream os )
	{
		super(os);
	}
	
	@Override
	/** just flush but do not close */
	public void close() throws IOException
	{
		flush();
	}
	
	public void reallyClose() throws IOException
	{
		super.close();
	}
}
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值