apache poi:无法重新打开工作簿:InvalidOperationException

apache poi: can't re-open workbook: InvalidOperationException

我有一种创建和写入 .xlsx 文件的方法,效果很好:

public static void createFileAndwriteResult(String path) {
    f = new File(path);
    try {
        f.createNewFile();
    } catch (IOException e1) {
        Message.showMessage("", "Permission to result folder denied", false);

    }
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(f);
        XSSFWorkbook wb = new XSSFWorkbook();
        Sheet resultSheet = wb.createSheet();
        //do stuff
        wb.write(fos);
        wb.close();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

还有另一种将内容附加到 .xlsx 的方法:

public static void appendToFile() {
    File f = new File(path);
    XSSFWorkbook wb = null;
    Sheet resultSheet = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(f);
        try {
            wb = new XSSFWorkbook(new FileInputStream(f)); // <--- This is where the exception happens
            resultSheet = wb.getSheetAt(0);
            //do stuff
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }

}

但是,如果我想重新打开该工作簿,则会收到 InvalidOperationException 消息:无法打开指定的文件:'PathToFile\file.xlsx'。该文件存在于该文件夹中。但是,当发生该异常时,大小更改为 0kB。我尝试了不同的方法,包括:

OPCPackage pkg = OPCPackage.open(f);
wb = new XSSFWorkbook(pkg);

和:

Workbook wb = WorkbookFactory.create(new File(f));

知道如何解决这个问题/重新打开以前在同一程序中编写/使用过的工作簿的方法吗?

您正在尝试打开一个文件 read,而您已经打开文件 write - 这是行不通的。两次引用文件 f

//You open an OUTPUT stream into File f here
fos = new FileOutputStream(f);
    try {
        //And here you try to read again
        wb = new XSSFWorkbook(new FileInputStream(f)); 

您可以为输出创建一个新文件,然后用 "new" 输出文件替换 "old" 输入。

fos = new FileOutputStream(f); 创建输出流,"append" 选项等于 false。所以内容被清除了。

您应该将 true 定义为 append 参数:

fos = new FileOutputStream(f, true);