1

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?

5
  • 1
    Why are you re-reading/re-initializing the workbook on each cell update? Commented Jan 30, 2013 at 5:38
  • @Perception updating adhocly.. but lately the updates are higher.. any suggestions? Commented Jan 30, 2013 at 5:41
  • 2
    I would recommend splitting your logic to separate the 'update data' logic from the 'read/save' logic. That way you can decide to, in some cases, do a single quick update, and in others, batch up a bunch of updates before saving the workbook. Commented Jan 30, 2013 at 5:47
  • @Perception thanks. can you provide a sample like how to split the logic? Commented Jan 30, 2013 at 5:52
  • 1
    looks like SAN3 wrote some code up. Thats pretty close to what I would have written as well. Commented Jan 30, 2013 at 5:57

1 Answer 1

3

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();
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.