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

时间:2015-12-04 16:54:55

标签: java excel apache-poi 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:无法打开指定的文件:&#39; PathToFile \ file.xlsx&#39;。该文件存在于该文件夹中。但是,当发生异常时,大小会更改为0kB。我尝试了不同的方法,包括:

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

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

知道如何修复此问题/重新打开以前在同一程序中编写/使用的工作簿的方法吗?

2 个答案:

答案 0 :(得分:1)

您正在尝试打开一个文件 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)); 

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

答案 1 :(得分:0)

fos = new FileOutputStream(f);使用&#34;附加&#34;创建输出流选项等于false。所以内容已经清除。

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

fos = new FileOutputStream(f, true);