2015-10-17 113 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. 
}