使用POI生成带zip的xlsx文件

我使用POI Api将xlsx文件中的数据导出,并将其添加到Zip文件中。 当我打开zip文件时,我没有任何xlsx文件,只有三个目录(docProps,xl和_rels)和一个文件[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> 

我发现我的解决scheme的一部分,但现在我有另一个问题:

初始职位的问题是处理stream。 因为我为Zip和Workbook使用了相同的outputStream。 解决scheme为每个工作簿创build了一个新的ByteArrayOutpuStream。

 // Write WB conntent in outputStream ByteArrayOutputStream wbOutputStream = new ByteArrayOutputStream(); wb.write(wbOutputStream); addEntry(zip, myObject.getFileName(), wbOutputStream); wbOutputStream.close(); 

但是…现在生成的Zip文件已损坏…

xlsx文件是一个zip文件。 您应该检查适用于结果的contentType参数的MIMEtypes。 请参阅docx,pptx等的什么是正确的MIMEtypes?

只需将工作簿写入BytearrayInputStream然后转换成字节数组在ZipOutPutStream中使用该字节数组

这个为我工作……………………..

response.setContentType( “应用程序/压缩”);

response.setHeader( “内容处置”, “附件;文件名= \” “+文件名+”。拉链\ “”);

workBook = getWorkbook(displayList,cfgType);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

ZipOutputStream zos = new ZipOutputStream(baos);

ByteArrayOutputStream fileBaos = new> ByteArrayOutputStream();

zos.putNextEntry(new ZipEntry(“Test.xlsx”));

workBook.write(fileBaos);

zos.write(fileBaos.toByteArray());

zos.putNextEntry(new ZipEntry(“Test1.xlsx”));

zos.write(fileBaos.toByteArray());

fileBaos.close(); zos.close();

。response.getOutputStream()写(baos.toByteArray()); response.flushBuffer();