我有这个 excel 表,用户可以在其中输入有关几何形状的信息。如您所见,单元格 C:3 已命名为“形状”,值为三角形。
代码的第一部分可以提取单元格的名称,下面的代码块可以打印特定单元格或范围内的值。我希望能够传递第一个代码提取的那些名称,而不是将它们硬编码到 String cname 中。换句话说,String cname 应该等于我的第一个循环提取的所有值,也许是嵌套循环?
公共类 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());
}
}
}
}
}
}