使用Apache POI查找需要在Java中找到的String的列号

Finding the column number of the String that needs to be found in Java using Apache POI

假设我需要在 Excel sheet 中找到字符串 "XXX",我不知道如何获取包含该单元格的列号和行号字符串.

Iterator<Row> it = XXXPresentSheet.iterator();          
while (it.hasNext()) {
    Row row = it.next();                
    Iterator<Cell> cellIter = row.cellIterator();

    while (cellIter.hasNext()) {
        String field1 = cellIter.next().getStringCellValue();               
        if (field1 == "XXX") {
            System.out.println(someMethodThatReturnsColumnNumber());
        }
    }
}

我可以使用单元格迭代器遍历行。但是当我遇到我想要的字符串时,我想得到那个列号。非常感谢任何帮助。谢谢

最简单的方法是实现您自己的变量,该变量将在 while(it.hasNext()) 循环的每次成功迭代中增加。

Iterator<Row> it = XXXPresentSheet.iterator();  
while(it.hasNext()) { 
    int column = 0;
    Row row = it.next();                
    Iterator<Cell> cellIter = row.cellIterator();
    while(cellIter.hasNext()) {
       column++;
       String field1 = cellIter.next().getStringCellValue();                
       if(field1 == "XXX") {
           System.out.println(column);
       }
    }
}

其中 column = 1(起始列),如果您希望从值 column = 0

开始,可以在第一个循环之后增加列

进一步阅读can be found in this alternative Whosebug question.

如果你问一个细胞很好,它会tell you what Column Number it is in. It will also tell you what Row Number it is in

所以,只需执行以下操作:

DataFormatter fmt = new DataFormatter();
for (Row r : sheet) {
   for (Cell c : r) {
       if ("ThingToLookFor".equals(fmt.formatCellValue(cell))) {
          // Found it!
          int columnIndex = c.getColumnIndex();
          int rowNumber = c.getRowNumber();
          // Get the Excel style reference, eg C12
          String ref = ((new CellReference(rowNumber,columnIndex)).formatAsString();
       }
   }
}

通过使用 DataFormatter,您可以获得要与任何单元格进行比较的字符串值,而不仅仅是字符串值。 CellReference 位是可选的,但如果您想查看匹配

的单元格的 Excel 样式引用,它会有所帮助