最近在做一个excel导出功能的时候,发现一个很严重的性能问题,只能导出4W条,再多不仅特别慢,导不出来,可能还会内存溢出。于是查了下资料,发现是poi 3.8以前的版本不支持大批量数据的导出,参考官方介绍
于是将jar包升级后,修改代码,最终能在5分钟内导出100W的数据。
POI 导出大量数据到Excel
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class ExcelUtil{
public void handleExcel(){
SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
Sheet sheet = workbook.createSheet();
try
{
Row hSSFRowHead = sheet.createRow(0);
for (int i = 0; i < headNames.length; i++)
{
hSSFCell hSSFCell = hSSFRowHead.createCell(i, HSSFCell.CELL_TYPE_STRING);
hSSFCell.setCellValue(new XSSFRichTextString(headNames[i]));
}
List prdList = getExcelDataList();
for (Object prd : prdList)
{
Row hSSFRowData = sheet.createRow(count);
createDataRows(hSSFRowData, (Map) prd, headsName);
Cell hSSFCell;
for (int i = 0; i < headsName.length; i++)
{
hSSFCell = hSSFRowData.createCell(i, HSSFCell.CELL_TYPE_STRING);
setStringValue(prd, headsName[i], hSSFCell);
}
//刷新内存
if (count % 1000 == 0)
{
((SXSSFSheet) sheet).flushRows();
}
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
ByteArrayOutputStream ot = new ByteArrayOutputStream();
workbook.write(ot);
//不调用此方法会在tomcat/temp/poifiles下生成 **.xml文件,并且不会清理,调用清理临时文件
workbook.dispose();
}
}
叔叔,阿姨给点钱买棒棒糖吃