大資料匯出POI之SXSSFWorkbook
poi3.7可以使用HSSFWorkbook匯出xls格式,經查資料量只能在65536;
poi3.7可以使用XSSFWorkbook匯出xlsx格式,資料量可達到100w,經過跟蹤程式碼發現構建資料起始特別快但當資料量到達5w左右時突然變的很慢,最後報出OutOfMemoryError:java heap space jvm記憶體溢位錯誤,調整jvm記憶體引數無效;
網上搜索得知poi3.8使用SXSSFWorkbook大大優化了大數量的匯出,經更換jar包後成功匯出!
POI中SXSSFWorkbook專門處理大資料方法:
OutputStream os = null;
try {
HttpServletResponse response = super.getResponse();
response.setContentType("application/force-download"); // 設定下載型別
String filename ="risk_event.xlsx";
response.setHeader("Content-Disposition","attachment;filename=" + filename); // 設定檔案的名稱
os = response.getOutputStream(); // 輸出流
SXSSFWorkbook wb = new SXSSFWorkbook(1000);//記憶體中保留 1000 條資料,以免記憶體溢位,其餘寫入 硬碟
//獲得該工作區的第一個sheet
Sheet sheet1 = wb.createSheet("sheet1");
int excelRow = 0;
//標題行
Row titleRow = (Row) sheet1.createRow(excelRow++);
for (int i = 0; i < columnList.size(); i++) {
Cell cell = titleRow.createCell(i);
cell.setCellValue(columnList.get(i));
}
for (int m = 0; m < cycleCount; m++) {
List<List<String>> eventStrList = this.convertPageModelStrList();
if (eventStrList!= null && eventStrList.size() > 0) {
for (int i = 0; i < eventStrList.size(); i++) {
//明細行
Row contentRow = (Row) sheet1.createRow(excelRow++);
List<String> reParam = (List<String>) eventStrList.get(i);
for (int j = 0; j < reParam.size(); j++) {
Cell cell = contentRow.createCell(j);
cell.setCellValue(reParam.get(j));
}
}
}
}
wb.write(os);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
} // 關閉輸出流
}
下面是我在網上查詢的關於SXSSFWorkbook構造方法api說明
SXSSFWorkbook構造方法API說明
public SXSSFWorkbook(int rowAccessWindowSize)
* Construct an empty workbook and specify the window for row access.
構造一個空的工作簿並指定對行訪問的視窗
* <p>
* When a new node is created via createRow() and the total number
當一個新的節點通過createRow()方法生成,並且未被清除的總的記錄數目
* of unflushed records would exceed the specified value, then the
將會超過給定的值時,那麼
* row with the lowest index value is flushed and cannot be accessed
索引值最小的那一行將被清除並且再也不能通過getRow()方法訪問到了
* via getRow() anymore.
* </p>
* <p>
* A value of -1 indicates unlimited access. In this case all
-1值表示不限制的訪問. 在這種情形下,
* records that have not been flushed by a call to flush() are available
所有的未被清除的記錄都可以通過呼叫flush方法來隨機訪問
* for random access.
* <p>
* <p></p>
* A value of 0 is not allowed because it would flush any newly created row
0值是不允許的,因為它會在還沒有指定單元格的情況下清除任何新建的行
* without having a chance to specify any cells.
* </p>