gpt4 book ai didi

java - Apache POI : can't re-open workbook: InvalidOperationException

转载 作者:行者123 更新时间:2023-11-30 03:08:51 25 4
gpt4 key购买 nike

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

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

最佳答案

您正在尝试打开一个已打开用于写入的文件读取 - 这是行不通的。两次引用文件 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"输出文件替换“旧”输入。

关于java - Apache POI : can't re-open workbook: InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34093477/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com