2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以將工作簿的名稱存儲(chǔ)在列表中,而不是存儲(chǔ)工作簿本身
private List<String> workbooks = new ArrayList();
重寫 createWorkbook 以僅存儲(chǔ) excel 工作表的名稱 重寫 write 方法,使其創(chuàng)建一個(gè)新工作簿,如下所示
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貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊
這個(gè)錯(cuò)誤主要發(fā)生在我們試圖寫入已經(jīng)關(guān)閉的工作簿的內(nèi)容時(shí)。
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"
為什么我們得到這個(gè)例外?看看這段代碼
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());
}
}
您可以注意到第二個(gè) try 塊是 try-with-resources 塊并且正在關(guān)閉工作簿,因此我們得到了異常。
我們只是通過刪除第二個(gè) 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());
}
}
您可以在這個(gè)答案的第一個(gè)代碼塊中注意到,我們在將內(nèi)容寫入文件后關(guān)閉工作簿。
在 finally 塊中調(diào)用的close方法將負(fù)責(zé)關(guān)閉XSSFWorkbook實(shí)例以及SXSSFWorkbook。
添加回答
舉報(bào)