poi导出大量数据excel内存溢出解决方案

 

Excel2003版最大行数是65536行。Excel2007开始的版本最大行数是1048576行。

Excel2003的最大列数是256列,2007以上版本是16384列。

 

poi导出excel,不使用模板的

http://happyqing.iteye.com/blog/2075985

 

xls格式导出使用HSSFWorkbook,(这个暂时没有好办法)

 

xlsx格式导出以前使用XSSFWorkbook,可以使用新的SXSSFWorkbook(poi3.8+)

 

Workbook wb = new SXSSFWorkbook(1000); //大于1000行时会把之前的行写入硬盘

 

Row,Cell还跟之前的一样

 

官方样例

http://poi.apache.org/spreadsheet/how-to.html#sxssf

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); // 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));
        }

        // 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();
    }

 

 值得注意的是SXSSFWorkbook只能写不能读。但是往往我们需要向一个Excel模版里导出数据,这样才更好提前定义里面的格式和vba代码。

这里就需要使用SXSSFWorkbook的另外一个构造函数:

SXSSFWorkbook(XSSFWorkbook workbook)
Construct a workbook from a template.

 通过XSSFWorkbook来读取模版,然后用SXSSFWorkbook来设置样式和写数据,详细使用就参考API吧。 http://poi.apache.org/apidocs/org/apache/poi/xssf/streaming/SXSSFWorkbook.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值