POI 导出大批量数据的Excel

POI作为操作Excel的三方库应用广泛,本文着重讨论导出大批量数据的Excel的处理,版本为4.1.0:

        
            org.apache.poi
            poi
            4.1.0
        

使用HSSFWorkbook进行导出,示例代码如下,代码中导出5万行20列的数据,相应时间见打印的情况:

package com.test.poi;

import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class Demo {

    public static void main(String[] args) throws IOException {
        testHSSFWorkbook();
    }

    static void testHSSFWorkbook() throws IOException {
        long start = System.currentTimeMillis();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < 20; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue("列" + i);
        }
        System.out.println("准备完表头时间:" + (System.currentTimeMillis() - start));
        for (int i = 0; i < 50000; i++) {
            HSSFRow rowInfo = sheet.createRow(i + 1);
            for (int j = 0; j < 20; j++) {
                HSSFCell cellInfo = rowInfo.createCell(j);
                cellInfo.setCellValue("列内容为" + j);
            }
        }
        System.out.println("准备完表内容时间:" + (System.currentTimeMillis() - start));
        FileOutputStream out = new FileOutputStream("D:\\test.xlsx");
        workbook.write(out);
        out.close();
        System.out.println("输入完成时间:" + (System.currentTimeMillis() - start));
        System.out.println("finish");
    }

}

输出结果为:

准备完表头时间:220
准备完表内容时间:1730
输入完成时间:4471
finish

你可能感兴趣的:(POI 导出大批量数据的Excel)