2015-10-17 131 views
3

我正在使用Apache POI库来读/写xlsx。在我原来的xlsx中,我有一个namedrange“XYZ”。Apache POI:更新指定范围内的单元格

我想更新这个名称范围内的单元格的值。我怎样才能做到这一点? 我这样做:

XSSFName name = workbook.getName("XYZ"); 
String formula = name.getRefersToFormula(); 
System.out.println("Formula = " + formula); 

现在,我不知道如何得到一个处理单个细胞在这个命名范围。

任何人都可以请我指出我可以使用正确的API吗?

RGDS 萨班

回答

5

有从Busy Developers' Guide为范围内检索单元的例子。然后你可以使用Cell.setCellValue()来更新。

// setup code 
String cname = "TestName"; 
Workbook wb = getMyWorkbook(); // retrieve workbook 

// retrieve the named range 
int namedCellIdx = wb.getNameIndex(cname); 
Name aNamedCell = wb.getNameAt(namedCellIdx); 

// retrieve the cell at the named range and test its contents 
AreaReference aref = new AreaReference(aNamedCell.getRefersToFormula()); 
CellReference[] crefs = aref.getAllReferencedCells(); 
for (int i=0; i<crefs.length; i++) { 
    Sheet s = wb.getSheet(crefs[i].getSheetName()); 
    Row r = s.getRow(crefs[i].getRow()); 
    Cell c = r.getCell(crefs[i].getCol()); 
    // extract the cell contents based on cell type etc. 
}