1

I am trying to update a column in the excel sheet but only the first row is getting update. The second iteration is not working. Could anyone help me on this? Below is my code that I am trying.

    String excelPath = "path";

    String YES = "Updated YES";
    String NO = "Updated NO";
    try {

        FileInputStream fis= new FileInputStream(excelPath);


        HSSFWorkbook  workSheet = new HSSFWorkbook(fis);
        Cell cell = null;
        FileOutputStream output_file =new FileOutputStream(excelPath);

        for (int i = 0; i < TCID.size(); i++) {
            HSSFSheet sheet1 = workSheet.getSheetAt(0);
            String data = sheet1.getRow(i+1).getCell(i).toString();

            if(data.equals(TCID.get(i))){

                cell = sheet1.getRow(i+1).getCell(i+2);
                cell.setCellValue(YES);                 
                workSheet.write(output_file);
            }else {
                cell.setCellValue(NO);
                workSheet.write(output_file);
            }               

        }

        fis.close();
        output_file.close();
        workSheet.close();

    }catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

My latest code is below. Now it is updating the columns but the last row is not getting updated. What am i missing.

FileInputStream fis= new FileInputStream(excelPath);

        HSSFWorkbook  workSheet = new HSSFWorkbook(fis);
        HSSFSheet sheet1 = workSheet.getSheetAt(0);
        //FileOutputStream output_file =new FileOutputStream(excelPath);
        for (int i = 0; i < TCID.size(); i++) {

            String data = sheet1.getRow(i+1).getCell(0).toString();
            Cell cell = sheet1.getRow(i+1).getCell(2);
            if(data.equals(TCID.get(i))){
                cell.setCellValue(YES);                 
            }else {
                cell.setCellValue(NO);
            }               

        }

        fis.close();
        //output_file.close();
        //workSheet.close();
        FileOutputStream output_file =new FileOutputStream(excelPath);
        workSheet.write(output_file);
        output_file.close(); 
4
  • In your else block` you are not populating the cell variable Commented Oct 28, 2019 at 6:27
  • i tried but still the same. Commented Oct 28, 2019 at 6:39
  • Also move HSSFSheet sheet1 = workSheet.getSheetAt(0); to before your for loop - add some debugging to make sure that you are looping more than once and if this does not solve your issue then edit your question with your latest code, Commented Oct 28, 2019 at 6:41
  • I have updated code and it is updating the columns, but not the full columns. My method signature has list. I am passing this list and i m comparing the first column of the excel. The expected result should be, if both the value matches, it should update the third column as Yes and remaining values should be updated as NO. I am not sure, if I am iterating the loop correctly. Right now I am iterating on the list, I think I should iterate on the entire first column. Let me know if it makes sense. Also how to iterate on the entire column ? Commented Oct 28, 2019 at 8:04

3 Answers 3

1

The row and the column are both keyed off 'i', so you'll be traversing the sheet diagonally.

But certainly do the things the other people are recommending too, they are all good suggestions.

Typically when working with a two dimensional block of information, I find it useful to have one loop for rows and then nested inside that a loop for columns (or vice versa)

e.g.

for (y = startRow; y <= maxRow; y++) {

  ....

  for (x = startCol; x <= maxCol; x++) {


     .... // do something to each column in the current row

     cell = sheet1.getRow(y).getCell(x);

     .....
Sign up to request clarification or add additional context in comments.

1 Comment

what you said is correct. It is updating diagonally. I want to use only one for loop.
1

Ok, so there are a couple of things.

  1. Declare HSSFSheet sheet1 = workSheet.getSheetAt(0); outside of your loop. You are working with the same sheet each iteration of your for loop, so this only has to be invoked once.
  2. Your logic to get the cell data (String data = sheet1.getRow(i+1).getCell(i).toString();) will not return you the same column. On your first iteration, you'll get (R)ow 1 : (C)olumn 0. The next iteration will return R2 : C1, then R2:C2, then R3:C3, etc. Notice the pattern that you are going diagonally down the columns, not vertically.
  3. Rows start at 0.
  4. You only need to workSheet.write(output_file); once you have done all your processing.
  5. If the Row does not exist you will get a NullPointerException
  6. As you are working with a unique Cell each iteration, you just declare it in the loop (so no need for Cell cell = null; outside your loop).

Here is a an example:

try {
  FileInputStream fis = new FileInputStream(excelPath);
  Workbook workbook = new HSSFWorkbook(fis);
  Sheet sheet = workbook.getSheetAt(0);
  for (int i = 0; i < 5; i++) {
    Row row = sheet.getRow(i);
    if (row != null) {
      Cell cell = row.getCell(0);
      cell.setCellValue("Updated cell.");
    }
  }
  FileOutputStream output_file =  new FileOutputStream(excelPath);
  workbook.write(output_file);
  output_file.close();
  fis.close();
} catch (Exception e) {
  e.printStackTrace();
}

1 Comment

@Sayeed, has your question been answered? If so please mark this as resolved, by checking the tick. Tx.
1

I think moving Cell reference inside for loop should fix it for you.

Cell cell = null;

Also you might also need to move outside if-block incase you face NullPointerException in else-block

cell = sheet1.getRow(i+1).getCell(i+2)

Something like this...

HSSFSheet sheet1 = workSheet.getSheetAt(0);
for (int i = 0; i < TCID.size(); i++) {
            String data = sheet1.getRow(i+1).getCell(0).toString();
            Cell cell = sheet1.getRow(i+1).getCell(2);
            if(data.equals(TCID.get(i))){
                cell.setCellValue(YES);                 
            }else {
                cell.setCellValue(NO);
            }
            workSheet.write(output_file)
       }

10 Comments

actually i am passing a list of ids and comparing this list with the first column values one by one. If the the value is not present in the first column then updating the third column as No. Below is the method signature. private static void updateExecutionStatus(List<String> TCID, String columnName, String excelSheetName, String sheetName)
Then simply adding line in else-block in your program should or moving it outside if-else should help you....... cell = sheet1.getRow(i+1).getCell(i+2); Let me know if it works for your need.
Thanks for the suggestion. It is updating diagonally and the last row is not updated.
It is updating diagonally because you are doing getCell(i+2), and if you see value of i is increasing in for loop. Saying that, you would need to use a fix value instead of using i to get cell reference. Check updated answer
Thanx for ur help. It is updating correctly now. Only the last row is not getting updated. I have posted my latest code in the question.
|

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.