Apache poi如何获取单元格坐标

Vla*_*mir 5 java excel cell coordinates apache-poi

我尝试获取单元格的坐标,现在我编写下一个代码:

for (Row row : sheet) {
   for(Cell cell : row){
      // how to get a cell coordinates?
   }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 7

获取单元格地址的最短方法是:

cell.getAddress().formatAsString()

要获取工作表名称,请执行以下操作

cell.getSheet().getSheetName()


Gag*_*arr 3

user2310289 建议了显而易见的解决方案,但这不起作用,因为迭代器会跳过空白行和单元格

因此,一种选择是手动迭代,处理空白单元格,然后您将始终知道单元格在哪里,代码如下:

// 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());
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您确实想使用简单的迭代器,则需要从单元格中查找行和单元格索引,例如

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());
   }
}
Run Code Online (Sandbox Code Playgroud)