在数据透视表中添加计算字段
Contents
[
Hide
]
可能的使用场景
当您基于已知数据创建数据透视表时,您会发现其中的数据不是您想要的。您想要的数据是这些原始数据的组合。例如,您需要在希望获取数据之前对原始数据进行加法、减法、乘法和除法。这时,您需要构建一个计算字段并设置相应的计算公式。然后对计算字段执行一些统计和其他操作。
在Excel的数据透视表中添加计算字段
在Excel中的数据透视表中插入计算字段,请按照以下步骤进行:
- 选择要向其添加计算字段的数据透视表。
- 转到功能区中的数据透视表分析选项卡。
- 单击“字段、项和集” ,然后从下拉菜单中选择“计算字段”。
- 在“名称”字段中输入计算字段的名称。
- 在“公式”字段中,输入要使用适当数据透视表字段名称和数学运算符执行的公式。
- 单击"确定"创建计算字段。
- 新的计算字段将出现在数据透视表字段列表中的值部分。
- 将计算字段拖动到数据透视表的值部分中,以显示计算值。
在数据透视表中添加计算字段
请参阅以下示例代码。 代码首先设置原始数据并创建数据透视表。 然后根据数据透视表中的现有PivotField创建计算字段,并将计算字段添加到数据区域。 最后,以 output XLSX 格式保存工作簿。 执行示例代码后,工作表上将添加带有计算字段的数据透视表。
示例代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Instantiating an Workbook object | |
Workbook workbook = new Workbook(); | |
//Obtaining the reference of the newly added worksheet | |
Worksheet ws = workbook.getWorksheets().get(0); | |
Cells cells = ws.getCells(); | |
//Setting the value to the cells | |
Cell cell = cells.get("A1"); | |
cell.putValue("Fruit"); | |
cell = cells.get("B1"); | |
cell.putValue("Count"); | |
cell = cells.get("C1"); | |
cell.putValue("Price"); | |
cell = cells.get("A2"); | |
cell.putValue("Apple"); | |
cell = cells.get("A3"); | |
cell.putValue("Mango"); | |
cell = cells.get("A4"); | |
cell.putValue("Blackberry"); | |
cell = cells.get("A5"); | |
cell.putValue("Cherry"); | |
cell = cells.get("B2"); | |
cell.putValue(5); | |
cell = cells.get("B3"); | |
cell.putValue(3); | |
cell = cells.get("B4"); | |
cell.putValue(6); | |
cell = cells.get("B5"); | |
cell.putValue(4); | |
cell = cells.get("C2"); | |
cell.putValue(5); | |
cell = cells.get("C3"); | |
cell.putValue(20); | |
cell = cells.get("C4"); | |
cell.putValue(30); | |
cell = cells.get("C5"); | |
cell.putValue(60); | |
//Adding a PivotTable to the worksheet | |
int i = ws.getPivotTables().add("=A1:C5", "D10", "PivotTable1"); | |
//Accessing the instance of the newly added PivotTable | |
PivotTable pivotTable = ws.getPivotTables().get(i); | |
pivotTable.addFieldToArea(PivotFieldType.ROW, 0); | |
//Adding a calculated field to PivotTable and drag it to data area. | |
pivotTable.addCalculatedField("total", "=Count*Price", true); | |
pivotTable.refreshData(); | |
pivotTable.calculateData(); | |
workbook.save("out.xlsx"); |