我正在使用 POI 3.2(我可以用于我的客户的最新版本)在 Java 中生成 Excel 文件。 这是我的代码。正如您所看到的,我正在使用 HSSF,因为我需要制作一个 XLS 文件。
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Reporting");
sheet.setColumnWidth(250,250);
HSSFRow Row;
HSSFCell Cell;
//Content part (doesn't matter)
IWDResource resource = WDResourceFactory.createCachedResource(
wb.getBytes(),
"workbook.xls",
WDWebResourceType.XLS);
wdContext.currentContextElement().setXls(resource);
现在,在我下载 XLS 文件后,我想打开它,但该文件似乎已损坏。
链接上的图片:http://tinyurl.com/nop52sh
当我按两次“不发送”时,Excel 文件会以正确的形式打开。
知道为什么吗?
最佳答案
不要调用wb.getBytes()
,它不会执行您想要的操作。来自 getBytes() javadoc
Method getBytes - get the bytes of just the HSSF portions of the XLS file. Use this to construct a POI POIFSFileSystem yourself.
相反,如果您希望整个 xls 文件作为字节数组,请执行
ByteArrayOutStream baos = new ByteArrayOutStream();
wb.write(baos);
byte[] xlsBytes = baos.toByteArray();
最后,Apache POI 3.2 已经很古老了,现在已经有 5 年多了!您确实应该升级,请参阅 changelog了解自那时以来修复的所有错误
关于java - POI 3.2 Excel 文件数据丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22229874/