在数据透视表中添加计算字段
Contents
[
Hide
]
可能的使用场景
当您基于已知数据创建数据透视表时,您会发现其中的数据不是您想要的。您想要的数据是这些原始数据的组合。例如,您需要在希望获取数据之前对原始数据进行加法、减法、乘法和除法。这时,您需要构建一个计算字段并设置相应的计算公式。然后对计算字段执行一些统计和其他操作。
在Excel的数据透视表中添加计算字段
在Excel中的数据透视表中插入计算字段,请按照以下步骤进行:
- 选择要向其添加计算字段的数据透视表。
- 转到功能区中的数据透视表分析选项卡。
- 单击“字段、项和集” ,然后从下拉菜单中选择“计算字段”。
- 在“名称”字段中输入计算字段的名称。
- 在"公式"字段中,输入要使用适当的数据透视表字段名称和数学运算符进行计算的公式。
- 单击"确定"创建计算字段。
- 新的计算字段将出现在数据透视表字段列表中的值部分。
- 将计算字段拖动到数据透视表的值部分中,以显示计算值。
通过C#在数据透视表中添加计算字段
使用Aspose.Cells向Excel文件中添加计算字段。请查看以下示例代码。执行示例代码后,数据透视表将添加一个带有计算字段的工作表。
- 设置原始数据并创建数据透视表。
- 根据数据透视表中现有的PivotField创建计算字段。
- 将计算字段添加到数据区。
- 最后,以[out.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.Worksheets[0]; | |
Aspose.Cells.Cells cells = ws.Cells; | |
//Setting the value to the cells | |
Aspose.Cells.Cell cell = cells["A1"]; | |
cell.PutValue("Fruit"); | |
cell = cells["B1"]; | |
cell.PutValue("Count"); | |
cell = cells["C1"]; | |
cell.PutValue("Price"); | |
cell = cells["A2"]; | |
cell.PutValue("Apple"); | |
cell = cells["A3"]; | |
cell.PutValue("Mango"); | |
cell = cells["A4"]; | |
cell.PutValue("Blackberry"); | |
cell = cells["A5"]; | |
cell.PutValue("Cherry"); | |
cell = cells["B2"]; | |
cell.PutValue(5); | |
cell = cells["B3"]; | |
cell.PutValue(3); | |
cell = cells["B4"]; | |
cell.PutValue(6); | |
cell = cells["B5"]; | |
cell.PutValue(4); | |
cell = cells["C2"]; | |
cell.PutValue(5); | |
cell = cells["C3"]; | |
cell.PutValue(20); | |
cell = cells["C4"]; | |
cell.PutValue(30); | |
cell = cells["C5"]; | |
cell.PutValue(60); | |
//Adding a PivotTable to the worksheet | |
int i = ws.PivotTables.Add("=A1:C5", "D10", "PivotTable1"); | |
//Accessing the instance of the newly added PivotTable | |
PivotTable pivotTable = ws.PivotTables[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"); |