我有一個 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 傳遞,并且不再打開。
[編輯:因為我被問到:
- 該檔案只被讀取,我從不寫它。
- apache POI 的版本是 3.15]
我該如何解決?
uj5u.com熱心網友回復:
您可以嘗試以下選項:
- 創建
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
s 僅用于使代碼正常作業,而不僅僅是在那里列印堆疊跟蹤。正如評論所說,您可能希望在catch
塊中做一些更好的事情。
作為替代方案,new XSSFWorkbook(fis)
您可以使用WorkbookFactory
in order to create(fis)
。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/470797.html
標籤:爪哇 擅长 apache-poi