Home » excel » Apache POI: Writing into excel with Java: opening Workbook, java.io.IOException: Cannot write data, document seems to have been closed already

Apache POI: Writing into excel with Java: opening Workbook, java.io.IOException: Cannot write data, document seems to have been closed already

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a class that stores Excel workbooks:

private Map<String, Workbook> workbooks = new HashMap();

public Workbook createWorkbook(String name)  {
    Workbook workbook = new XSSFWorkbook();
    workbooks.put(name, workbook);
    return workbook;
}

and a method that writes into a workbook with a specified name:

public void write(List<ExcelData> data, String workbookName) {
   Workbook workbook = workbooks.get(workbookName);
   CreationHelper createHelper = workbook.getCreationHelper();

   ... write stuff

   FileOutputStream fileOut = new FileOutputStream(workbookName + ".xlsx");
   workbook.write(fileOut);
   fileOut.close();

   workbook.close();
}

However when I try to call method write two times for the same workbook:

testExcel.write(data, "Default");
testExcel.write(data1, "Default");

I get

Exception in thread "main" java.io.IOException: Cannot write data, document seems to have been closed already

error. I know I can open existing Excel workbook like this:

FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = WorkbookFactory.create(inputStream);

But I was wondering if there’s a way to bypass it by storing a Workbook variable. What are the inner mechanics at play? Is the variable becomes invalid after workbook.write() is called?

How to&Answers:

Instead of storing the workbook itself you can store the name of work book in list
private List workbooks = new ArrayList();
Rewrite the createWorkbook to store only the name of the excel sheet
Rewrite the write method so it creates a new workbook as follows
public void write(List data, String workbookName) {

Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();

… write stuff

 FileOutputStream fileOut = new FileOutputStream(workbookName + ".xlsx");
 workbook.write(fileOut);
 fileOut.close();

 workbook.close();
}