在数据透视表中添加计算字段

可能的使用场景

当您基于已知数据创建数据透视表时,您会发现其中的数据不是您想要的。您想要的数据是这些原始数据的组合。例如,您需要在希望获取数据之前对原始数据进行加法、减法、乘法和除法。这时,您需要构建一个计算字段并设置相应的计算公式。然后对计算字段执行一些统计和其他操作。

如何在Excel中的数据透视表中添加计算字段

在Excel中的数据透视表中插入计算字段,请按照以下步骤进行:

  1. 选择要向其添加计算字段的数据透视表。
  2. 转到功能区中的数据透视表分析选项卡。
  3. 单击“字段、项和集” ,然后从下拉菜单中选择“计算字段”。
  4. 在“名称”字段中输入计算字段的名称。
  5. 在"公式"字段中,输入要使用适当的数据透视表字段名称和数学运算符进行计算的公式。
  6. 单击"确定"创建计算字段。
  7. 新的计算字段将出现在数据透视表字段列表中的值部分。
  8. 将计算字段拖动到数据透视表的值部分中,以显示计算值。

如何使用Aspose.Cells for Python Excel库向数据透视表中添加计算字段

使用Aspose.Cells for Python via .NET在Excel文件中添加计算字段。请参阅以下示例代码。执行示例代码后,数据透视表中将添加一个具有计算字段的数据透视表。

  1. 设置原始数据并创建数据透视表。
  2. 根据数据透视表中现有的PivotField创建计算字段。
  3. 将计算字段添加到数据区。
  4. 最后,以[out.xlsx]格式保存工作簿。

示例代码

from aspose.cells import Workbook
from aspose.cells.pivot import PivotFieldType
# Instantiating an Workbook object
workbook = Workbook()
# Obtaining the reference of the newly added worksheet
ws = workbook.worksheets[0]
cells = ws.cells
# Setting the value to the cells
cell = cells.get("A1")
cell.put_value("Fruit")
cell = cells.get("B1")
cell.put_value("Count")
cell = cells.get("C1")
cell.put_value("Price")
cell = cells.get("A2")
cell.put_value("Apple")
cell = cells.get("A3")
cell.put_value("Mango")
cell = cells.get("A4")
cell.put_value("Blackberry")
cell = cells.get("A5")
cell.put_value("Cherry")
cell = cells.get("B2")
cell.put_value(5)
cell = cells.get("B3")
cell.put_value(3)
cell = cells.get("B4")
cell.put_value(6)
cell = cells.get("B5")
cell.put_value(4)
cell = cells.get("C2")
cell.put_value(5)
cell = cells.get("C3")
cell.put_value(20)
cell = cells.get("C4")
cell.put_value(30)
cell = cells.get("C5")
cell.put_value(60)
# Adding a PivotTable to the worksheet
i = ws.pivot_tables.add("=A1:C5", "D10", "PivotTable1")
# Accessing the instance of the newly added PivotTable
pivotTable = ws.pivot_tables[i]
pivotTable.add_field_to_area(PivotFieldType.ROW, 0)
# Adding a calculated field to PivotTable and drag it to data area.
pivotTable.add_calculated_field("total", "=Count*Price", True)
pivotTable.refresh_data()
pivotTable.calculate_data()
workbook.save("out.xlsx")