![](/img/trans.png)
[英]Excel file gets corrupted after overwrite in Android with apache poi
[英]Excel file gets corrupted after launching an executable jar
我有一個 Eclipse 項目,其中包含以下使用 Apache POI 的代碼。
public static void main(String[] args){
try{
XSSFWorkbook sourceWorkbook = new XSSFWorkbook("input.xlsx");
XSSFSheet sheet = sourceWorkbook.getSheetAt(0);
// do stuff
sourceWorkbook.close();
} catch (IOException e){
e.printStackTrace();
}
}
當我從 Eclipse 啟動它時,它工作正常。 由於我創建了可執行文件 jar,當我使用它時,Excel 輸入文件從 9 增加到 1 kB,並且不再打開。
[編輯:因為有人問我:
我該如何解決?
您可以嘗試以下選項:
FileInputStream
到工作簿路徑try
-with-resources 語句中執行此操作try
塊內的工作簿也許像這樣:
public static void main(String[] args) {
String wbPath = "input.xlsx";
// use an auto-closable resource stream
try (FileInputStream fis = new FileInputStream(wbPath)) {
// then use that in order to open the workbook
Workbook workbook = new XSSFWorkbook(fis);
// then open the sheet
Sheet sheet = workbook.getSheetAt(0);
// and do stuff…
// Having done stuff, close the workbook explicitly
workbook.close();
// and let the try with resources close the input stream
} catch (FileNotFoundException e) {
// do proper exception handling here
throw new RuntimeException("file " + wbPath + " seems not to exist");
} catch (IOException e) {
// do proper exception handling here, too
throw new RuntimeException("error during read or write operation");
}
}
RuntimeException
僅用於使代碼正常工作,而不僅僅是在那里打印堆棧跟蹤。 正如評論所說,您可能想在catch
塊中做一些更好的事情。
作為new XSSFWorkbook(fis)
的替代方案,您可以使用WorkbookFactory
來create(fis)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.