我正在尝试使用命名范围来获取单元格。但是尝试了以下代码之后,无法在使用r.getCell()的工作表行中获得一致异常的行中获得一致的单元格。

String cname = "TestName";
Workbook wb = getMyWorkbook(); // retrieve workbook

// retrieve the named range
int namedCellIdx = wb.getNameIndex(cellName);
Name aNamedCell = wb.getNameAt(namedCellIdx);

// retrieve the cell at the named range and test its contents
AreaReference aref = new AreaReference(aNamedCell.getRefersToFormula());
CellReference[] crefs = aref.getAllReferencedCells();
for (int i = 0; i < crefs.length; i++) {
    Sheet s = wb.getSheet(crefs[i].getSheetName());
    Row r = sheet.getRow(crefs[i].getRow());
    Cell c = r.getCell(crefs[i].getCol());
    // extract the cell contents based on cell type etc.
}

最佳答案

为了节省内存,表上没有存储完全空的行。同样,完全空的单元格不会存储在工作表的行中。

如果未在工作表上定义行,则Sheet.getRow返回null。如果在该行中未定义单元格,Row.getCell还将返回null。

所以我们总是需要检查:

...
Row r = sheet.getRow(crefs[i].getRow());
if (r == null) {
 //row is empty
} else {
 Cell c = r.getCell(crefs[i].getCol());
 if (c == null) {
  //cell is empty
 } else {
  //do soomething with c
 }
}
...

09-26 03:00