java-在Servlet端使用Excel表格生成内存中的zip文件
作者:互联网
在这里,基本上我正在尝试将excel表格的zip文件从服务器发送到客户端.
方法1:我的Servlet代码
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
for(Map.Entry<String, List<Data>> entry : DatasMap.entrySet())
{
String fileName = entry.getKey();
List<Data> excelData = entry.getValue();
// The below code constructs the workbook and returns it
SXSSFWorkbook workBook = getWorkBook(fileName, excelData);
ZipEntry zipEntry = new ZipEntry(fileName );
zos.putNextEntry(zipEntry);
workBook.write(zos);
zos.closeEntry(); // getting error at this line
}
错误:
SEVERE: Servlet.service() for servlet [MyApp-server] in context with path [/myapp-server] threw exception
java.io.IOException: Stream closed
at java.util.zip.ZipOutputStream.ensureOpen(ZipOutputStream.java:82)
at java.util.zip.ZipOutputStream.closeEntry(ZipOutputStream.java:231)
方法2:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos);
ServletOutputStream out = response.getOutputStream();
for(Map.Entry<String, List<Data>> entry : DatasMap.entrySet())
{
String fileName = entry.getKey();
List<Data> excelData = entry.getValue();
// The below code constructs the workbook and returns it
SXSSFWorkbook workBook = getWorkBook(fileName, excelData);
ZipEntry zipEntry = new ZipEntry(fileName );
zos.putNextEntry(zipEntry);
workBook.write(bos);
bos.writeTo(zos)
zos.closeEntry(); // this line works perfectly in this case
}
zos.close();
byte[] bytes = bos.toByteArray();
//setting content-type and zip file name
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=Templates.zip");
out.write(bytes);
out.flush();
方法2可以正常工作,但是当我尝试在客户端打开zip文件时,出现错误提示错误提取
我不确定excel工作表是否已损坏或任何其他服务器端流问题.如果有任何有益的想法/想法,请与我分享.
解决方法:
您的第二次尝试失败,因为您是通过直接将工作簿写入基础ByteArrayOutputStream来混合压缩内容和未压缩内容.因此,生成的zip文件被搞砸了.
第一次尝试失败,因为workBook.write关闭ZipOutputStream并在写入第二个条目时收到Stream关闭异常.
但是您可以防止流关闭.创建一个无法关闭的帮助器OutputStream类:
public class NonCloseableOutputStream extends java.io.FilterOutputStream {
public NonCloseableOutputStream(OutputStream out) {
super(out);
}
@Override public void close() throws IOException {
flush();
}
}
并将该类的实例传递给工作簿:
// The below code constructs the workbook and returns it
SXSSFWorkbook workBook = getWorkBook(fileName, excelData);
ZipEntry zipEntry = new ZipEntry(fileName );
zos.putNextEntry(zipEntry);
workBook.write(new NonCloseableOutputStream(zos));
zos.closeEntry();
标签:zip,stream,apache-poi,java,excel 来源: https://codeday.me/bug/20191118/2029091.html