我想写读取和使用下面的代码写入到工作簿:的Apache POI文件中获取损坏,无法写入现有工作簿
public static void main(String args[]) {
String absoluteFilePath = System.getProperty("user.dir") + File.separator + "abc.xlsx";
System.out.println("Readin file : " + absoluteFilePath);
Workbook workbook = null;
try {
workbook = WorkbookFactory.create(new File(absoluteFilePath));
//reading and writing on sheets of workbook
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
System.out.println("Writing to workbook and Closing the file");
FileOutputStream fileOutputStream = new FileOutputStream(
new File(absoluteFilePath));
workbook.write(fileOutputStream);
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
当我运行的第一次的代码,我在workbook.write(fileOutputStream);
Exception in thread "main" org.apache.poi.POIXMLException: java.io.IOException: Can't obtain the input stream from /docProps/app.xml
at org.apache.poi.POIXMLDocument.getProperties(POIXMLDocument.java:148)
at org.apache.poi.POIXMLDocument.write(POIXMLDocument.java:199)
at NewNewDriver.main(NewNewDriver.java:129)
Caused by: java.io.IOException: Can't obtain the input stream from /docProps/app.xml
at org.apache.poi.openxml4j.opc.PackagePart.getInputStream(PackagePart.java:500)
at org.apache.poi.POIXMLProperties.<init>(POIXMLProperties.java:75)
at org.apache.poi.POIXMLDocument.getProperties(POIXMLDocument.java:146)
... 2 more
得到这个例外,在此之后,该工作簿被破坏,我减少到0KB和我得到WorkbookFactory.create()
此异常:
org.apache.poi.poifs.filesystem.NotOLE2FileException: Invalid header signature; read 0x0000000000000000, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:167)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:117)
at org.apache.poi.poifs.filesystem.NPOIFSFileSystem.<init>(NPOIFSFileSystem.java:225)
at org.apache.poi.poifs.filesystem.NPOIFSFileSystem.<init>(NPOIFSFileSystem.java:164)
at org.apache.poi.poifs.filesystem.NPOIFSFileSystem.<init>(NPOIFSFileSystem.java:145)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:105)
at NewNewDriver.main(NewNewDriver.java:27)
Closing the file
Exception in thread "main" java.lang.NullPointerException
at NewNewDriver.main(NewNewDriver.java:129)
我应该在哪里以及如何使用FileOutputStream,workbook.write(),并且我也应该使用FileInputStream,即使我正在使用WorkbookFactory?
------------编辑----------------------我得到我的代码工作 我用FileInputStream而不是WorkbookFactory创建工作簿并在关闭FileOutputStream后关闭它。这工作。
这是什么版本的Apache POI?如果不是3.11最终版(最新版),升级时会发生什么? – Gagravarr
该版本是最新版本 - 3.11 – tanvi