问题描述
我有一个 Cell 对象,我怎样才能得到那个 Cell 的名字?
I have a Cell object, how can I get the name of that cell?
想要一个函数,例如:
String name = myCell.getName();
在Excel中我已经在名称框中命名了,所以我不想得到'B4',我想得到诸如InterestRate"之类的名称.
In Excel I have named it in the name box, so I don't want to get 'B4', I would like to get the name such as "InterestRate".
找不到这样的方法,能不能用别的方法实现?
Can't find such a method, can I achieve it in some other way?
推荐答案
要查找定义为与一个单元格完全匹配的命名范围,您需要如下内容:
To find the named range which is defined to exactly match one cell, you'd want something like:
// 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();
}
}
}
请注意,这将返回适用于单元格的第一个命名范围,如果有多个并且您想要全部,则需要调整该代码以继续并返回列表
Note that this will return the first named range that applies to a cell, if there's more than one and you wanted them all, you'd need to tweak that code to keep going and return a list
这篇关于获取单元格 apache poi 的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!