Home » excel » JAVA – Apache POI batch modify Excel File

JAVA – Apache POI batch modify Excel File

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am running a java application that modify large excel file. And I am experiencing the time it takes an update to take place..

for each cell I am running the update based on the changes as fallows

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

Is there any optimizations that I can make to my code?

How to&Answers:

Open the excel once ,after all your update operation close the excel.

Example :

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