在Excel文件中,如何使用Java设置单元格名称

时间:2019-01-22 12:33:29

标签: java apache-poi

我有一个Excel文件。我想为特定的单元格设置一个唯一的名称。 但是没有称为“ cell.setName”的方法。

2 个答案:

答案 0 :(得分:2)

关于官方文档:

命名范围是一种通过名称引用一组单元格的方法。命名单元格是命名范围的简并的情况,因为“单元格组”恰好包含一个单元格。您可以在工作簿中按其命名范围创建和引用单元格。使用命名范围时,将使用org.apache.poi.ss.util.CellReference和org.apache.poi.ss.util.AreaReference类。

注意:使用诸如“ A1:B1”之类的相对值可能会导致在Microsoft Excel中使用工作簿时该名称指向的单元格的意外移动,通常使用诸如“ $ A $ 1:$ B $ 1”之类的绝对引用避免这种情况,另请参阅此讨论。

Creating Named Range / Named Cell

    // setup code
    String sname = "TestSheet", cname = "TestName", cvalue = "TestVal";
    Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet(sname);
    sheet.createRow(0).createCell(0).setCellValue(cvalue);

    // 1. create named range for a single cell using areareference
    Name namedCell = wb.createName();
    namedCell.setNameName(cname + "1");
    String reference = sname+"!$A$1:$A$1"; // area reference
    namedCell.setRefersToFormula(reference);

    // 2. create named range for a single cell using cellreference
    Name namedCel2 = wb.createName();
    namedCel2.setNameName(cname + "2");
    reference = sname+"!$A$1"; // cell reference
    namedCel2.setRefersToFormula(reference);

    // 3. create named range for an area using AreaReference
    Name namedCel3 = wb.createName();
    namedCel3.setNameName(cname + "3");
    reference = sname+"!$A$1:$C$5"; // area reference
    namedCel3.setRefersToFormula(reference);

    // 4. create named formula
    Name namedCel4 = wb.createName();
    namedCel4.setNameName("my_sum");
    namedCel4.setRefersToFormula("SUM(" + sname + "!$I$2:$I$6)");

链接:https://poi.apache.org/components/spreadsheet/quick-guide.html#NamedRanges

答案 1 :(得分:0)

// setup code
String sname = "TestSheet", cname = "TestName", cvalue = "TestVal";
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet(sname);
sheet.createRow(0).createCell((short) 0).setCellValue(cvalue);

// 1. create named range for a single cell using areareference
Name namedCell = wb.createName();
namedCell.setNameName(cname);
String reference = sname+"!A1:A1"; // area reference
namedCell.setRefersToFormula(reference);

来自:http://poi.apache.org/components/spreadsheet/quick-guide.html#NamedRanges