【问题标题】:JAVA - Apache POI batch modify Excel FileJAVA - Apache POI 批量修改 Excel 文件
【发布时间】:2013-01-30 13:54:44
【问题描述】:

我正在运行一个修改大型 excel 文件的 java 应用程序。而且我正在经历需要进行更新的时间..

对于每个单元格,我都会根据变化运行更新

  public boolean updateCellData(ColumnName, RowNum, Data){
    FileInputStream fis = new FileInputStream(path);
        Workbook    workbook = WorkbookFactory.create(fis);

        row =  getRow(rowNum-1);
            if (row == null){
                row = sheet.createRow(rowNum-1);
            }
            cell = row.getCell(colNum);
            if (cell == null){
                cell = row.createCell(colNum);
            }
            cell.setCellValue(data);
            fileOut = new FileOutputStream(path);
            workbook.write(fileOut);
            fileOut.close();
    }

我可以对我的代码进行任何优化吗?

【问题讨论】:

  • 为什么要在 每个 单元格更新时重新阅读/重新初始化工作簿?
  • @Perception 临时更新.. 但最近更新更高.. 有什么建议吗?
  • 我建议您拆分逻辑,将“更新数据”逻辑与“读取/保存”逻辑分开。这样,您可以决定在某些情况下进行一次快速更新,而在其他情况下,在保存工作簿之前批量更新。
  • @Perception 谢谢。你能提供一个如何拆分逻辑的示例吗?
  • 看起来 SAN3 编写了一些代码。这也非常接近我会写的内容。

标签: java excel memory optimization apache-poi


【解决方案1】:

打开excel一次,完成所有更新操作后关闭excel。

示例:

      FileInputStream fis =null;
     Workbook workbook=null;
    public void openWorkbook(){
         fis = new FileInputStream(path);
         workbook = WorkbookFactory.create(fis);
    }

    public boolean updateCellData(ColumnName, RowNum, Data){

            row =  getRow(rowNum-1);
                if (row == null){
                    row = sheet.createRow(rowNum-1);
                }
                cell = row.getCell(colNum);
                if (cell == null){
                    cell = row.createCell(colNum);
                }
                cell.setCellValue(data);
      }

    public void closeWorkbook(){
        fileOut = new FileOutputStream(path);
        workbook.write(fileOut);
        fileOut.close();
    }

【讨论】:

    猜你喜欢
    • 2015-06-30
    • 1970-01-01
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多