如何使用Apache POI获取MS Excel单元格的名称和内容

我有这个Excel表格,用户input关于几何形状的信息。 正如你所看到的单元格C:3已经被命名为“形状”,值是三angular形。 在这里输入图像说明

代码的第一部分可以拉出单元格的名称,下面的块可以打印特定单元格或范围内的值。 我希望能够传递第一个代码的名字,而不是硬编码到String cname中。 换句话说,string的名称应该等于我的第一个循环拉的所有值,也许一个嵌套循环?

公共类RangeSetter {

public static void main(String[] args) throws IOException { // File Location FileInputStream file = new FileInputStream(new File("test2.xls")); HSSFWorkbook wb = new HSSFWorkbook(file); // retrieve workbook // This part of the code pulls all the names of the cells int NameTotalNumber = wb.getNumberOfNames(); for (int NameIndex = 0; NameIndex < NameTotalNumber; NameIndex++) { Name nameList = wb.getNameAt(NameIndex); System.out.println("AliasName: " + nameList.getNameName()); } // This part reads a cell depending of the name // This is string has the name of the cell I want to read String cname = "Shape"; // Retrieve the named range int namedCellIdx = wb.getNameIndex(cname); Name aNamedCell = wb.getNameAt(namedCellIdx); AreaReference[] arefs = AreaReference.generateContiguous(aNamedCell .getRefersToFormula()); for (int i = 0; i < arefs.length; i++) { // Only get the corners of the Area // (use arefs[i].getAllReferencedCells() to get all cells) CellReference[] crefs = arefs[i].getAllReferencedCells(); for (int j = 0; j < crefs.length; j++) { // Check it turns into real stuff Sheet s = wb.getSheet(crefs[j].getSheetName()); Row r = s.getRow(crefs[j].getRow()); Cell c = r.getCell(crefs[j].getCol()); if (c != null) { switch (c.getCellType()) { case Cell.CELL_TYPE_STRING: System.out.println(c.getStringCellValue()); } } } } } }