APACHE POI 按列名格式设置公式

APACHE POI set formula by column name format

当我想按列名格式将公式设置为单元格时出现小问题。让我举个例子:

在 excel 文件中我可以做这样的事情 =[Name]

所以 B 列的值被复制到 A 列

但是当我尝试在 Apache POI 中做这样的事情时

  cell.setCellFormula("[Name]");

我遇到异常:

Parse error near char 0 '[' in specified formula '[Name]'. Expected number, string, defined name, or data table"

我该如何处理这种情况?

公式=[Name]是一个structured reference to an Excel table。但这是一个非常短的不合格表格。完全限定的形式将是 =tableName[[#This Row],[Name]],并且该完全限定的形式也将被存储,因此必须使用 apache poi.

进行设置

我们来看一个完整的例子:

import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;

class CreateExcelTableUsingStructuredReferences {

 public static void main(String[] args) throws Exception {

  try (XSSFWorkbook workbook = new XSSFWorkbook();
       FileOutputStream fileout = new FileOutputStream("./Excel.xlsx") ) {

   //data
   String[] tableHeadings = new String[]{"Id", "Name", "Description"};
   String[] tableContent = new String[]{null, "Name1", "Description1"};
   //variables
   String tableName = "Table1";
   int firstRow = 0; //start table in row 1
   int firstCol = 0; //start table in column A
   int rows = 2; //we have to populate headings row and 1 data row
   int cols = 3; //three columns in each row
   
   //prepairing the sheet
   XSSFSheet sheet = workbook.createSheet();
   
   //set sheet content  
   for (int r = 0; r < rows; r++) { 
    XSSFRow row = sheet.createRow(firstRow+r);
    for (int c = 0; c < cols; c++) { 
     XSSFCell localXSSFCell = row.createCell(firstCol+c);
     if (r == 0) {
      localXSSFCell.setCellValue(tableHeadings[c]);
     } else {
      localXSSFCell.setCellValue(tableContent[c]);
     }
    }
   }
   
   //create the table
   CellReference topLeft = new CellReference(sheet.getRow(firstRow).getCell(firstCol));
   CellReference bottomRight = new CellReference(sheet.getRow(firstRow+rows-1).getCell(firstCol+cols-1));
   AreaReference tableArea = workbook.getCreationHelper().createAreaReference(topLeft, bottomRight);
   XSSFTable dataTable = sheet.createTable(tableArea);
   dataTable.setName(tableName);
   dataTable.setDisplayName(tableName);
   
   //set table column formula
   dataTable.getCTTable().getTableColumns().getTableColumnList().get(0).addNewCalculatedColumnFormula().setStringValue(
      tableName + "[[#This Row],[Name]]");

   //set the formula in sheet
   XSSFCell formulaCell = sheet.getRow(firstRow+1).getCell(firstCol);
   formulaCell.setCellFormula(tableName + "[[#This Row],[Name]]");
   //following is not necessary up to apache poi 5.1.0, but later versions of apache poi uses formula parser which damages structured table formulas
   formulaCell.getCTCell().getF().setStringValue(tableName + "[[#This Row],[Name]]");
   
   workbook.write(fileout);
  }

 }
}

这适用于 apache poi 4 或更高版本。

注意,仅在 5.1.0 之后使用 apache poi 版本才需要额外的 formulaCell.getCTCell().getF().setStringValue(tableName + "[[#This Row],[Name]]");apache poi 的更高版本使用破坏结构化 table 公式的公式解析器,因此必须使用此代码行重置它。