XSSFWorkbook对象的write方法内会将传入的资源流自动关闭 导致下载excel失败
错误代码
OutputStream out = response.getOutputStream();
ZipOutputStream zos = new ZipOutputStream(out);
XSSFWorkbook workbook = new XSSFWorkbook();
// 将文件写入zip内,即将文件进行打包
zos.putNextEntry(new ZipEntry(fileName + "(" + UUID.randomUUID() + ")." + typeName));
// 此处将自动关闭zos资源
workbook.wirte(zos);
解决方法: 将XSSFWorkbook转换成ByteArrayOutputStream,用ByteArrayOutputStream对象将流写入zip对象中
OutputStream out = response.getOutputStream();
ZipOutputStream zos = new ZipOutputStream(out);
XSSFWorkbook workbook = new XSSFWorkbook();
// 将文件写入zip内,即将文件进行打包
zos.putNextEntry(new ZipEntry(fileName + "(" + UUID.randomUUID() + ")." + typeName));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
bos.writeTo(zos);
zos.closeEntry();
// 当所有文件打包完成后关闭zos资源
zos.close();
原文地址:https://www.cnblogs.com/bradcai/p/11344247.html
时间: 2024-10-29 07:05:42