Anish6595
Anish6595

Reputation: 108

APACHE POI, how to find the row index of a cell?

     col1          col2    col3   col4
row1
row2
row3
row4
row5 Row Labels    sum1    sum2   sum3 
row6 blah          100      78      88
row7 blah          200      5      8
row8 blah          300      400   500

Im using tha apahe poi to find the row index of the "Row Labels". the code im using to do this is:

for(int i=0;i<r;i++){
        Row temprow=ws.getRow(i);
        for(int j=0;j<ws.getRow(0).getLastCellNum();j++){
            Cell cell=temprow.getCell(j);
            try{ 
                if(cell.getStringCellValue().equals("Row Labels")){
                    temp=j;
                    break;
                }
            }catch(Exception e){
                continue;
            }
        }
        break;
    }

how ever the value of temp is always coming as zero when it should be coming as 4, cant seem to find my mistake. help! thanks

Upvotes: 0

Views: 10366

Answers (2)

SANN3
SANN3

Reputation: 10109

You need the row index so assign the i value not the j value. "Row Labels" is in the zero th column so only it returning always 0.

for(int i=0;i<r;i++){
        Row temprow=ws.getRow(i);
        for(int j=0;j<ws.getRow(0).getLastCellNum();j++){
            Cell cell=temprow.getCell(j);
            try{ 
                if(cell.getStringCellValue().equals("Row Labels")){
                    temp=i; // Check here
                    break;
                }
            }catch(Exception e){
                continue;
            }
        }
        break;
    }

Upvotes: 0

Gagravarr
Gagravarr

Reputation: 48376

Promoting a comment to an answer... Your problem is that you're recording the value of j, the column counter, not i, the row counter!

If it were me, I'd re-write your code slightly as:

int headingRow = -1;
for(int rn=0;rn<r;rn++){
    Row temprow=ws.getRow(rn);
    if (temprow == null) {
      // This row is all blank, skip
      continue
    }
    for(int cn=0;cn<temprow.getLastCellNum();cn++){
        Cell cell=temprow.getCell(cn);
        if (cell == null) {
           // No cell here
        } else {
           try{ 
               // This bit is very nasty...
               if(cell.getStringCellValue().equals("Row Labels")){
                  headingRow=cn;
                  break;
               }
           }catch(Exception e){
              continue;
           }
        }
    }
    break;
}

Well, I might rewrite it a bit more, but at least that code has more helpful variable names to track what's happening, checks for empty rows and cells etc!

Upvotes: 1

Related Questions