【发布时间】:2014-10-07 03:49:41
【问题描述】:
我使用 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);
}
}
这段代码写在一个注入到 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>
【问题讨论】: