获取单元格名称 Apache POI

4

我有一个单元格(Cell)对象,如何获取该单元格的名称?

需要一个类似这样的函数:

String name = myCell.getName();

在Excel中,我已经在名称框中命名了它,所以我不想得到“B4”,我想得到名称,例如“InterestRate”。找不到这样的方法,我能用其他方法实现吗?

你的意思是想获取一个单元格所属的命名区域,如果有的话?还是其他什么? - Gagravarr
@Gagravarr 是的,没错,如果命名范围与命名单元格相同(具有一个元素的命名范围?) - Viktor Mellgren
1个回答

6

要查找与单元格完全匹配的命名区域,您需要类似以下内容:

// Get the cell we want to find - A1 for this case
Workbook wb = WorkbookFactory.create("input.xlsx");
int sheetIndex = 0;
Sheet s = wb.getSheetAt(sheetIndex);
Cell wanted = s.getRow(0).getCell(0);
String wantedRef = (new CellReference(wanted)).formatAsString();

// Check all the named range
for (int nn=0; nn<wb.getNumberOfNames(); nn++) {
   Name n = wb.getNameAt(nn);
   if (n.getSheetIndex() == -1 || n.getSheetIndex() == sheetIndex) {
      if (n.getRefersToFormula().equals(wantedRef)) {
         // Found it!
         return name.getNameName();
      }
   }
}

请注意,如果一个单元格有多个命名区域,并且您想要它们全部返回,则需要对代码进行调整以继续执行并返回列表中的所有命名区域。请注意,此代码将返回适用于单元格的第一个命名区域。

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