簡體   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

我使用tha apahe poi查找“行標簽”的行索引。 我用於執行此操作的代碼是:

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

當temp的值應該變為4時,temp的值為何總是變為零,似乎無法發現我的錯誤。 救命! 謝謝

在評論中添加注釋...您的問題是您正在記錄j的值(列計數器,而不是i ,行計數器)!

如果是我,我會稍微重新編寫一下您的代碼:

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

好吧,我可能會再重寫一點,但是至少該代碼具有更有用的變量名來跟蹤正在發生的事情,檢查空行和單元格等!

您需要行索引,因此請分配i值而不是j值。 行標簽 ”位於第零列,因此只有其始終返回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