我有这个excel Sheet,用户输入有关几何形状的信息。如您所见,单元格C:3已命名为“Shape”,值为三角形。
代码的第一部分可以提取单元格的名称,以下块可以在特定单元格或范围内打印值。我希望能够传递第一个代码提取的名称,而不是将它们硬编码为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());
}
}
}
}
}
}