当前位置: 动力学知识库 > 问答 > 编程问答 >

xssf - Apache POI - How to write XSSFWorkbook to POIFSFileSystem?

问题描述:

Using Apache POI HSSF, we can create xls file like this

private void write(HSSFWorkbook workbook) {

POIFSFileSystem filesystem = new POIFSFileSystem();

filesystem.createDocument(new ByteArrayInputStream(workbook.getBytes()),

"Workbook");

FileOutputStream stream = new FileOutputStream("test.xls");

filesystem.writeFilesystem(stream);

}

Similarly, how can I write with XSSFWorkbook? This does not have the getBytes() method.

I tried to create ByteArrayInputStream from XSSFWorkbook like this -

ByteArrayOutputStream baos = new ByteArrayOutputStream();

workbook.write(baos); //XSSFWorkbook here

ByteArrayInputStream bias = new ByteArrayInputStream(baos.toByteArray());

But the xlsx file created was corrupt. How can I write the workbook to disc using POIFSFileSystem?

The same XSSFWorkbook was written sucessfully when I did like this -

FileOutputStream stream = new FileOutputStream("test.xlsx");

workbook.write(stream);

When I extracted and compared the xlsx files, there was no difference. However, when I do a plain text compare on the xlsx files directly (without extracting), there are few differences in the bytes.

So the problem should be in the createDocument() and/or writeFilesystem() methods of POIFSFileSystem. Can someone let me know how to write XSSFWorkbook using POIFSFileSystem?

网友答案:

You can't!

POIFSFileSystem works with OLE2 files, such as .xls, .doc, .ppt, .msg etc. The POIFS code handles reading and writing the individual streams within that for you.

With the OOXML files (.xlsx, .docx, .pptx etc), the container for the file is no longer OLE2. Instead, the files are stored within a Zip container. In POI, this is handled by OPCPackage, which takes care of reading and writing from Zip files with the required OOXML metadata.

If you want to write a XSSF file to disk, simply do:

FileOutputStream stream = new FileOutputStream("test.xlsx");
workbook.write(stream);
stream.close();

And XSSFWorkbook will handle talking to OPCPackage for you to make that happen.

分享给朋友:
您可能感兴趣的文章:
随机阅读: