首页 文章

Apache POI:更新命名范围内的单元格

提问于
浏览
4

我正在使用Apache POI库来读/写xlsx . 在我原来的xlsx中,我有一个命名范围“XYZ” .

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

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

现在,我不知道如何在这个命名范围内获得单个单元格的句柄 .

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

Rgds Sapan

1 回答

  • 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.
    }
    

相关问题