我想寫讀取和使用下面的代碼寫入到工作簿:的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