【问题标题】:Excel Writing becomes slow after writing more than 5000 rows in JAVAJAVA写入超过5000行后Excel写入变慢
【发布时间】:2020-03-04 17:39:55
【问题描述】:

在excel文件中写入5000行后会在excel中写入缓慢。

谁能建议我如何加快编写 excelfile 的速度?

我正在使用 selenium - java 从我的网站抓取数据

当我开始编写代码时,编写速度很快,但 1 小时后变得很慢。 (CPU和RAM消耗正常。)

这是编写excel文件的代码。

public boolean setCellData(String sheetName,String colName,int rowNum, String data){
        try{
        fis = new FileInputStream(path); 
        workbook = new XSSFWorkbook(fis);

        if(rowNum<=0)
            return false;

        int index = workbook.getSheetIndex(sheetName);
        int colNum=-1;
        if(index==-1)
            return false;


        sheet = workbook.getSheetAt(index);


        row=sheet.getRow(0);
        for(int i=0;i<row.getLastCellNum();i++){
            //System.out.println(row.getCell(i).getStringCellValue().trim());
            if(row.getCell(i).getStringCellValue().trim().equals(colName)) {
                colNum=i;
                break;
            }
        }
        if(colNum==-1)
            return false;

        sheet.autoSizeColumn(colNum); 
        row = sheet.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();    

        }
        catch(Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

【问题讨论】:

    标签: java


    【解决方案1】:

    让我们看看:

    • 将整个工作表加载到内存中
    • 更新一个单元格
    • 将整个工作表写回文件
    • 对下一行/单元格重复所有操作

    现在为什么会这么慢?
    因为读写文件很慢。

    你应该:

    • 加载工作表一次
    • 更新所有需要更新的行/单元格
    • 将结果保存回文件

    【讨论】:

      【解决方案2】:

      保留对工作表和行的引用,而不是每次设置值时都查找它们。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-11
        • 1970-01-01
        • 2013-02-02
        • 2020-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多