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

我有一个方法来创build和写一个.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(); } } } 

但是,如果我想重新打开该工作簿,则会得到一个InvalidOperationExceptionexception:无法打开指定的文件:“PathToFile \ file.xlsx”。 该文件存在于该文件夹中。 但是,发生exception时,大小会变为0kB。 我试过不同的方法,包括:

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

和:

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

任何想法如何解决这个/重新打开一个工作簿,这是写在同一个程序之前使用的方式吗?

fos = new FileOutputStream(f); 用“append”选项创build一个输出stream等于false。 所以内容被清除。

你应该定义为trueappend参数:

 fos = new FileOutputStream(f, true); 

你正试图打开一个文件来阅读 ,你已经打开 – 这是行不通的。 两次你引用文件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)); 

您可以创build一个新的文件输出,然后用“新”输出文件replace“旧”input。