简体   繁体   English

APACHE POI,如何找到一个单元格的行索引?

[英]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". 我使用tha apahe poi查找“行标签”的行索引。 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. 当temp的值应该变为4时,temp的值为何总是变为零,似乎无法发现我的错误。 help! 救命! thanks 谢谢

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! 在评论中添加注释...您的问题是您正在记录j的值(列计数器,而不是i ,行计数器)!

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! 好吧,我可能会再重写一点,但是至少该代码具有更有用的变量名来跟踪正在发生的事情,检查空行和单元格等!

You need the row index so assign the i value not the j value. 您需要行索引,因此请分配i值而不是j值。 " Row Labels " is in the zero th column so only it returning always 0. 行标签 ”位于第零列,因此只有其始终返回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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM