java - 大型 Excel 工作表生成优化

标签 java excel apache-poi

我正在尝试使用 POI 库生成一个包含近 13000 行和 3 列的 .xls 文件。但是生成完整的文件需要将近 8-10 分钟。谁能建议我如何减少执行时间?

public static void generateReconReport(Connection con,String neName,String reportTable) throws SQLException, IOException{
    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

    String sql = "SELECT * FROM "+reportTable;
    ResultSet rsNERecon = stmt.executeQuery(sql);

    System.out.println("Resulset obtained, Generating Report");

    Date date = new Date();
    SimpleDateFormat sid = new SimpleDateFormat("MMddyyyy");
    String curDate = sid.format(date);

    String fileName = neName.toUpperCase()+"_" + curDate + ".xlsx";

    File ob_file = new File(fileName);
    if(!ob_file.exists())
        ob_file.createNewFile();

    HSSFWorkbook hsfWb = new HSSFWorkbook();

    HSSFSheet hsfSheet =  hsfWb.createSheet(neName.toUpperCase()+" Recon Report");

    HSSFRow hsfRow = hsfSheet.createRow(0);

    ResultSetMetaData metaRs = rsNERecon.getMetaData();
    int colCount = metaRs.getColumnCount();

    for (int j = 1; j <= colCount; j++) {
        String colName = metaRs.getColumnName(j);
        hsfRow.createCell(j).setCellValue(colName);
    }
    FileOutputStream fileOut =  new FileOutputStream(fileName);
    int rowNum = 1;
    while (rsNERecon.next()) {
        hsfRow = hsfSheet.createRow(rowNum);
        for (int j = 1; j <= colCount; j++) 
            hsfRow.createCell(j).setCellValue(rsNERecon.getString(j));
        rowNum++;
    }

    for (int j = 1; j <= colCount; j++) 
        hsfSheet.autoSizeColumn(j);

    rsNERecon.close();
    stmt.close();

    hsfWb.write(fileOut);
    fileOut.close();
    System.out.println("Report generated for "+neName.toUpperCase());
}

最佳答案

使用制表符或逗号作为分隔符生成字符分隔值文件 (csv) 会更快。使用 .csv 扩展名保存文件。

Excel 读取这些文件的速度非常快。

关于java - 大型 Excel 工作表生成优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21017231/

相关文章:

带有动画 GIF 的 JavaFX OutOfMemoryError

java - 使用 selenium 将图像添加到 Excel 工作表的单元格

Excel VLOOKUP 函数无法返回换行符

excel - 如何在 excel VBA 用户窗体中显示 excel 工作表图表

vba - 如何在VBA、Excel中复制和选择图表、图片等

java - 如何替换单元格值 - Apache POI

java - JAVA 中的 Excel 到 Json 转换器

java - Apache CXF 2.4.6 到 2.5.3 升级

java - Spring/JPA/persistence实体属性字段不能是final的?

java - 无法在 Android AVD 上运行我的项目