Excel 文件在启动可执行 jar 后损坏

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");
    }
}

RuntimeExceptions 只是为了使代码工作,而不仅仅是在那里打印堆栈跟踪。正如评论所说,您可能想在 catch 块中做一些更好的事情。

作为 new XSSFWorkbook(fis) 的替代方法,您可以使用 WorkbookFactorycreate(fis)