如何在 Python 中创建数据透视表

这个简短的教程指导在 Python 中创建数据透视表,并借助详细的步骤提供有关环境配置和 Python 程序流程的信息。使用 Python Excel 数据透视表 时,将在加载包含数据透视表输入数据的源工作簿后使用可运行的示例代码创建。最后,生成的工作簿将以任何所需的格式保存,例如 XLSXXLS 等。

在 Python 中创建数据透视表的步骤

  1. 建立环境以通过 Java 安装 Aspose.Cells for Python 进入项目
  2. 加载或创建包含数据透视表输入数据的 Workbook 类对象
  3. 在目标 worksheet 中获取对数据透视表集合的引用
  4. 在集合中添加数据透视表
  5. 配置新添加的数据透视表
  6. 将所需字段添加到数据透视表中的相应区域
  7. 保存带有数据透视表的输出工作簿

这些步骤通过共享指向环境配置资源的链接以及要在 Python 中执行以实现功能的任务序列,为 Python 代码在 Excel 中创建数据透视表提供了说明。它指导根据要求将字段添加到数据透视表中的不同区域。准备好数据透视表后,它会以所需格式保存在 Excel 文件中。

使用 Python 创建 Excel 数据透视表的代码

import jpype
import csv
import asposecells
jpype.startJVM()
from asposecells.api import License, Workbook, PivotFieldType, LoadOptions,FileFormatType
# Instantiate a license to avoid watermark in the output Excel file having pivot table
cellsLicense = License()
cellsLicense.setLicense("Aspose.Cells.lic")
header = ['City', 'Class', 'Fee']
data = [
['Islamabad','Class 1',750],
['Islamabad','Class 4',1000],
['Karachi','Class 1',300],
['Karachi','Class 4',750],
['Karachi','Class 1',2035],
['Karachi','Class 4',2500],
['Islamabad','Class 1',3215]
]
with open('data.csv', 'w', encoding='UTF8', newline='') as f:
writer = csv.writer(f)
# write the header
writer.writerow(header)
# write the data
writer.writerows(data)
# Create a CSV LoadOptions class object
csvLoadOptions = LoadOptions(FileFormatType.CSV)
# Load the CSV data into Workbook class object using the load options
csvWorkbook = Workbook("data.csv",csvLoadOptions)
# Get access to the first sheet for adding pivot table to it
wsPivotTable = csvWorkbook.getWorksheets().get(0)
# Get access to pivot tables collection in the selected sheet
pivotTablesCollection = wsPivotTable.getPivotTables()
# Create the pivot table and save its index
pivotTableIndex = pivotTablesCollection.add("=A1:C8", "A10", "PythonPivotTable")
# Get access to the newly created pivot table
newPivotTable = pivotTablesCollection.get(pivotTableIndex)
# set flag to hide grand totals for rows
newPivotTable.setRowGrand(False)
# Add the first field to the column area of the pivot table
newPivotTable.addFieldToArea(PivotFieldType.COLUMN, 0)
# Add the second field to the row area of the pivot table
newPivotTable.addFieldToArea(PivotFieldType.ROW, 1)
# Add the third field to the data area
newPivotTable.addFieldToArea(PivotFieldType.DATA, 2)
# Saving the Excel file
csvWorkbook.save("NewPivotTable.xlsx")
jpype.shutdownJVM()
Python 中的这些代码行使用加载的 Excel 文件中的数据创建 Excel 数据透视表。请注意,如果您已经有一个包含数据的 Excel 文件并加载它,则可以跳过创建工作簿。此代码还通过将 RowGrand 标志设置为 False 来隐藏各个行的总计来演示新创建的数据透视表的自定义,而您还可以进行其他自定义,例如设置更改文本的标题、设置列大、自定义列表排序, ETC。

本文指导我们创建数据透视表。如果您想阅读受密码保护的 Excel 文件,请参阅文章 在 Python 中读取受密码保护的 Excel 文件

 简体中文