Apache POI如何获取单元格坐标

5

我尝试获取单元格的坐标,目前我编写了以下代码:

for (Row row : sheet) {
   for(Cell cell : row){
      // how to get a cell coordinates?
   }
}

如何获取单元格的坐标 (dx1, dx2, dy1, dy2)?

3个回答

7

获取单元格地址的最短方式为:

cell.getAddress().formatAsString()

获取工作表名称可以按以下步骤进行:

cell.getSheet().getSheetName()


3
显而易见的解决方案是由用户2310289提出的(参见此处),但是这并不适用于迭代器跳过空行和空单元格的情况。
因此,一个选项是手动迭代,处理空单元格,然后你将始终知道你的单元格在哪里,使用如下代码:
// Decide which rows to process
int rowStart = Math.min(15, sheet.getFirstRowNum());
int rowEnd = Math.max(1400, sheet.getLastRowNum());

for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
   Row r = sheet.getRow(rowNum);

   int lastColumn = Math.max(r.getLastCellNum(), MY_MINIMUM_COLUMN_COUNT);

   for (int cn = 0; cn < lastColumn; cn++) {
      Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
      if (c == null) {
         // The spreadsheet is empty in this cell
      } else {
         // Do something useful with the cell's contents
         CellReference cr = new CellReference(c);
         System.out.println("Cell at " + rowNum + "," + cn + " found, that's " + cr.formatAsString());
      }
   }
}

或者,如果您确实想使用简单的迭代器,您需要从单元格中查找行和列索引,例如:
for (Row r : sheet) {
   for (Cell c : r) {
       int columnNumber = c.getColumnIndex();
       int rowNumber = c.getRow().getRowNum();
       CellReference cr = new CellReference(c);
       System.out.println("Cell at " + rowNum + "," + columnNumber + " found, that's " + cr.formatAsString());
   }
}

我本以为会有更好的方法。但是根据他的其他问题,看起来原帖作者真正想要的是另外一件事。我将删除我的回答。 - Scary Wombat
为什么要将rowEnd的最大值设为1400?这样做有必要吗?如果行数超过了1400,整个文件就无法被处理。 - RTF
根据您的使用情况进行设置,或者完全删除它,完全由您决定!这只是一个示例,说明如何限制行。 - Gagravarr

1
我已经编写了以下代码以获取Excel单元格的坐标。希望这能对你有所帮助。
public static void searchSheet(String searchText, XSSFSheet sheet)
{

    int flag=0;
    for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++)
    {
        XSSFRow row = sheet.getRow(i);
        for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++)
        {
            XSSFCell cell = row.getCell(j);
            String CellData=cell.toString();
            if(searchText.equals(CellData))
            {
                flag=1;
                CellData=row.getCell(j+1).toString();
                System.out.println(CellData);
                System.out.println("String Found At Row="+ i +" and At Column="+j);


            }

         }
        break;
    }

    if(flag==0)
    {
        System.out.println("String Not Found");
    }

}

我不明白为什么你要加上这一行 CellData=row.getCell(j+1).toString(); 而你已经有了这个, String CellData=cell.toString();无论如何,我很感激你友善地回答了我的问题并提供了一个有用的搜索解决方案。 - Ishimwe Aubain Consolateur

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接