2 回答

TA貢獻1802條經驗 獲得超5個贊
您可以將工作簿的名稱存儲在列表中,而不是存儲工作簿本身
private List<String> workbooks = new ArrayList();
重寫 createWorkbook 以僅存儲 excel 工作表的名稱 重寫 write 方法,使其創建一個新工作簿,如下所示
public void write(List<ExcelData> data, String workbookName) {
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
... 寫東西
FileOutputStream fileOut = new FileOutputStream(workbookName + ".xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
}

TA貢獻1783條經驗 獲得超4個贊
這個錯誤主要發生在我們試圖寫入已經關閉的工作簿的內容時。
public void writeToExcel(File file) throws IOException {
LOGGER.debug("Writing chunks data to excel {}", file);
try (FileOutputStream outputStream = new FileOutputStream(file)) {
workbook.write(outputStream);
} catch (IOException e) {
LOGGER.error("Exception raised while writing chunks of items {}", e.getLocalizedMessage());
} finally {
// This line will take of closing XSSFWorkbook along with SXSSFWorkbook
workbook.close();
}
}
這段代碼是拋出以下異常的代碼
Exception thrown is:
Exception raised while writing chunks of items
"Cannot write data, document seems to have been closed already"
為什么我們得到這個例外?看看這段代碼
private void instructionSheet(Resource resource) {
try {
InputStream in = resource.getInputStream();
// This is try-with-resources block which is closing the XSSFWorkbook
try (XSSFWorkbook xssfwb = new XSSFWorkbook(OPCPackage.open(in))) {
workbook = new SXSSFWorkbook(xssfwb);
}
} catch (IOException | InvalidFormatException e) {
LOGGER.error("The instruction sheet failed to create {}", e.getLocalizedMessage());
}
}
您可以注意到第二個 try 塊是 try-with-resources 塊并且正在關閉工作簿,因此我們得到了異常。
我們只是通過刪除第二個 try 塊來解決它,即
private void instructionSheet(Resource resource) {
try {
workbook = new SXSSFWorkbook(new XSSFWorkbook(OPCPackage.open(resource.getInputStream())));
} catch (IOException | InvalidFormatException e) {
LOGGER.error("The instruction sheet failed to create {}", e.getLocalizedMessage());
}
}
您可以在這個答案的第一個代碼塊中注意到,我們在將內容寫入文件后關閉工作簿。
在 finally 塊中調用的close方法將負責關閉XSSFWorkbook實例以及SXSSFWorkbook。
添加回答
舉報