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

问题描述 投票:1回答:3

我有一种创建和写入.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));

任何想法如何解决此问题/重新打开以前在同一程序中编写/使用过的工作簿的方法?

java excel apache-poi invalidoperationexception
3个回答
0
投票

fos = new FileOutputStream(f);创建一个输出流,其中“ append”选项等于false。这样就清除了内容。

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

fos = new FileOutputStream(f, true);

1
投票

您正在尝试打开一个已经向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));

您可以创建一个新文件进行输出,然后将“旧”输入替换为“新”输出文件。

-4
投票
我也可以操你的屁股。我们谈论存在文件的问题。工作簿wb = new WorkbookFactory.create(new File(fpath)); -s not working can找不到创建方法。是的,我确实导入了org.apache.poi.ss.usermodel.WorkbookFactory;和钢铁什么都没有
© www.soinside.com 2019 - 2024. All rights reserved.