工作中遇到大数据导出excel内存溢出的问题,在使用jxl和POI3.8之前的版本都找不到很好的解决办法,通过设置jvm内存效果也不理想。但是在POI3.8以上版本中提供了SXSSFWorkbook的新类,可以通过参数设置常驻内存中的行数,防止OOM异常!
但是SXSSFWorkbook仅仅支持excel2007格式,也就是说SXSSFWorkbook只支持.xlsx格式,不支持.xls格式。在写入excel时,需要生成大量的数据的时候,通过刷新的方式将excel内存信息刷新到硬盘的方式,提供写入数据的效率。以下是导出的例子:
import junit.framework.Assert;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
public static void main(String[] args) throws Throwable {
SXSSFWorkbook wb = new SXSSFWorkbook(100); //设置最大行数,如果不想做限制可以设置为-1
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));
}
// ther 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();
}
但是有些客户要求是2003excel,当导出大数据是就比较复杂,下面的连接是我在网上看的一些资料,网上的做法大多数是分批导出之后再打包成压缩文件供用户下载,也有的是导出后再合并多个excel文件的方式!!
http://blog.youkuaiyun.com/yrsheng/article/details/4100393
使用SXSSFWorkbook解决大数据导出Excel内存溢出问题
本文介绍了解决大数据导出Excel时出现内存溢出的方法,使用Apache POI SXSSFWorkbook类可以有效避免OOM异常。该类允许设置常驻内存中的行数上限,并采用刷新方式提高写入效率。
2472

被折叠的 条评论
为什么被折叠?



