[]
        
(Showing Draft Content)

计算项

计算项是数据透视表项,使用包含常量的自定义公式或引用数据透视表中的其他项。这些项可以添加到数据透视表的行或列字段区域,但在源数据中不存在。

在GcExcel中,ICalculatedItems接口表示特定数据透视表中计算项的集合。您可以使用 IPivotField.getCalculatedItems 获取此数据透视项集合。ICalculatedItems 接口提供了 add 方法将计算项目添加到数据透视表中,该方法接受项的名称和公式作为参数。您也可以使用 IPivotItem.setFormula 方法设置计算项的公式。要从 ICalculatedItems 集合中删除计算项可以使用 remove 方法,该方法接受目标字段的名称作为参数。透视缓存管理所有计算项,因此更改计算项会影响当前工作簿中使用相同缓存的所有透视表。此外,计算项中的任何类型的添加、删除或更改都会触发透视表更新。

注意: 以下行为会抛出异常:

  • 当数据透视表中存在计算项时,将相同字段添加到数据字段部分。

  • 当数据字段具有两个或多个相同字段时,添加计算项。

  • 添加具有已用名称的计算项。计算项的名称参数不区分大小写。因此,透视表认为 “Formula” 和 “formula” 名称相同。

请参考以下代码在数据透视表中创建计算项:

// Get the calculated item for the specified field
ICalculatedItems countryCalcItems = calculatedItemTable.getPivotFields().get("Country").getCalculatedItems();
ICalculatedItems productCalcItems = calculatedItemTable.getPivotFields().get("Product").getCalculatedItems();

// add some calculated items using formulas
countryCalcItems.add("Oceania", "=Australia+NewZealand");
countryCalcItems.add("America", "=Canada");
IPivotItem myPivotItem = countryCalcItems.add("Europe", "=France");
        
// Change the formula of the calculated item
myPivotItem.setFormula("=France+Germany");
        
// Add calculated item using constant value
productCalcItems.add("IPhone 13", "=2500");
        
// Get the calculatedItems count
System.out.println("Calculated Items count: " + countryCalcItems.getCount());
        
// Remove a calculated item
countryCalcItems.remove("America");