我有一个 Cell 对象,如何获取该单元格的名称?
想要一个功能,例如:
String name = myCell.getName();
在 Excel 中,我在名称框中为其命名,所以我不想得到“B4”,我想得到诸如“InterestRate”之类的名称。
找不到这样的方法,我可以通过其他方式实现吗?
最佳答案
要找到被定义为与一个单元格完全匹配的命名范围,您需要这样的东西:
// 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();
}
}
}
请注意,这将返回适用于单元格的第一个命名范围,如果有多个命名范围并且您想要它们,您需要调整该代码以继续并返回一个列表
关于java - 获取单元格apache poi的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26649598/