我有一个存储 Excel 工作簿的类:
private Map<String, Workbook> workbooks = new HashMap();
public Workbook createWorkbook(String name) {
Workbook workbook = new XSSFWorkbook();
workbooks.put(name, workbook);
return workbook;
}
以及写入具有指定名称的工作簿的方法:
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();
}
但是,当我尝试为同一个工作簿调用方法write两次时:
testExcel.write(data, "Default");
testExcel.write(data1, "Default");
我得到
Exception in thread "main" java.io.IOException: Cannot write data, document seems to have been closed already
错误。我知道我可以像这样打开现有的 Excel 工作簿:
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = WorkbookFactory.create(inputStream);
但我想知道是否有办法通过存储Workbook变量来绕过它。有什么内在机制在起作用?workbook.write()调用后变量是否失效?
慕后森
慕娘9325324
相关分类