我使用 POI Api 将数据导出到 xlsx 文件中,并将它们添加到 Zip 文件中。当我打开 zip 时,我没有任何 xlsx 文件,而是三个目录(docProps、xl 和 _rels)和 1 个文件 [Content_Types] xml。我认为这是 xlsx 文件的描述,但我不明白为什么。
代码:
public InputStream exportXlsx(List<MyObject> listeOfObject) throws IOException {
ByteArrayOutputStream excelOutputStreamZip = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(excelOutputStreamZip);
for (MyObject myObject : listeOfObject) {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet wsheet = wb.createSheet("mySheet");
XSSFRow row = wsheet.createRow(0);
XSSFCell cell = row.createCell(1);
cell.setCellValue(myObject.getValue1());
// Create all sheet and cell....
// Write WB conntent in outputStream
wb.write(excelOutputStreamZip);
addEntry(zip, myObject.getFileName(), excelOutputStreamZip);
}
InputStream inputStreamZipByte = new ByteArrayInputStream(
((ByteArrayOutputStream) excelOutputStreamZip).toByteArray());
zip.close();
return inputStreamZipByte;
}
public void addEntry(OutputStream zip, String filename, ByteArrayOutputStream os) {
byte[] bytes = os.toByteArray();
ZipEntry entry = new ZipEntry(filename);
Date d = new Date();
entry.setTime(d.getTime());
try {
((ZipOutputStream) zip).putNextEntry(entry);
((ZipOutputStream) zip).write(bytes);
((ZipOutputStream) zip).closeEntry();
} catch (IOException e) {
log.error("Can't read the file !", e);
} catch (ClassCastException cce) {
log.error("Bad format !", cce);
}
}
此代码是在服务中编写的,该服务被注入(inject)到 Struts2 操作中。
struts.xml:
<action name="*MyAction" class="com.omb.view.action.myAction" method="{1}">
<result name="export" type="stream">
<param name="contentType">application/zip</param>
<param name="inputName">inputStreamZipByte</param>
<param name="contentDisposition">attachment;filename="myZip.zip"</param>
<param name="bufferSize">1024</param>
</result>
</action>
最佳答案
我找到了解决方案的一部分,但现在我遇到了另一个问题:
最初的帖子的问题在于流的处理。因为我对 Zip 和工作簿使用了相同的输出流。解决方案是为每个工作簿创建一个新的 ByteArrayOutpuStream。
// Write WB conntent in outputStream
ByteArrayOutputStream wbOutputStream = new ByteArrayOutputStream();
wb.write(wbOutputStream);
addEntry(zip, myObject.getFileName(), wbOutputStream);
wbOutputStream.close();
但是...现在生成的 Zip 文件已损坏...
关于java - 生成 zip 中包含 POI 的 xlsx 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25292034/