我從資料庫中獲得每個請求 50 萬條記錄,然后將資料映射到 POJO 類串列,然后將記錄寫入 Excel 作業表(我需要將資料匯出到 Excel 作業表),有沒有更好的方法生成“.xlsx”檔案?在這里,我需要迭代串列(回圈)(50 萬次)獲取記錄,然后將記錄寫入 .xlsx 檔案。
有沒有更好的方法來做到這一點,以獲得更好的性能并減少記憶體使用?
uj5u.com熱心網友回復:
如果您使用streamingAPI 代替普通 API ,Apache POI 的性能將得到極大的提升。POI 將在您寫入時將所有資料保存在記憶體中,對于大檔案,這可能會非常昂貴。您可以做的是使用流 API 并指示 POI 逐步重繪 資料。
以下是 POI 網站的示例:
public static void main(String[] args) throws Throwable {
SXSSFWorkbook wb = new SXSSFWorkbook(100); // keep 100 rows in memory, exceeding rows will be flushed to disk
Sheet sh = wb.createSheet();
for(int rownum = 0; rownum < 1000; rownum ){
Row row = sh.createRow(rownum);
for(int cellnum = 0; cellnum < 10; cellnum ){
Cell cell = row.createCell(cellnum);
String address = new CellReference(cell).formatAsString();
cell.setCellValue(address);
}
}
// Rows with rownum < 900 are flushed and not accessible
for(int rownum = 0; rownum < 900; rownum ){
Assert.assertNull(sh.getRow(rownum));
}
// the last 100 rows are still in memory
for(int rownum = 900; rownum < 1000; rownum ){
Assert.assertNotNull(sh.getRow(rownum));
}
FileOutputStream out = new FileOutputStream("/temp/sxssf.xlsx");
wb.write(out);
out.close();
// dispose of temporary files backing this workbook on disk
wb.dispose();
}
查看Apache POI 的網站了解更多資訊。(在 SXSSF(流用戶模型 API)下)
uj5u.com熱心網友回復:
嘗試 Apache POI 專案 ( https://poi.apache.org/ )。或 Aspose,但它不是開源的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/355785.html
