实现excel大数据量导出
导出Excel时,如果数据量较大,全部查询出来list,然后写入Workboook,会出现内存异常异常,建议使用SXSSFWorkbook,然后设置setCompressTempFiles属性为true
@Test
public void testBigExcel(){
try {
long startTime = System.currentTimeMillis();
final int NUM_OF_ROWS = 1300000;
final int NUM_OF_COLUMNS = 21;
SXSSFWorkbook wb = null;
try {
wb = new SXSSFWorkbook();
//压缩临时文件,很重要,否则磁盘很快就会被写满
wb.setCompressTempFiles(true);
Sheet sh =null;
int sheetNum=1;
int rowNum = 0;
for (int num = 0; num < NUM_OF_ROWS; num++) {
if (num % 1000000 == 0) {
sh = wb.createSheet("Sheet " + sheetNum);
rowNum = 0;
sheetNum++;
}else{
rowNum++;
}
org.apache.poi.ss.usermodel.Row row = sh.createRow(rowNum);
for (int cellNum = 0; cellNum < NUM_OF_COLUMNS; cellNum++) {
Cell cell = row.createCell(cellNum);
cell.setCellValue(Math.random());
}
}
FileOutputStream out = new FileOutputStream("d:/Maruko.xlsx");
wb.write(out);
out.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (wb != null) {
wb.dispose();// 删除临时文件,很重要,否则磁盘可能会被写满
}
}
long endTime = System.currentTimeMillis();
System.out.println("花费时间为:" + (endTime - startTime));
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}