How to Create Pivot Table in Python

This brief tutorial directs to create pivot table in Python with the help of detailed steps providing information about the environment configuration and Python program flow. While using Python Excel pivot table will be created using a runnable sample code after loading the source workbook containing the input data for the pivot table. In the end, the resultant workbook will be saved in any of the desired formats like XLSX, XLS, etc.

Steps to Create Pivot Table in Python

  1. Establish the environment to install Aspose.Cells for Python via Java into the project
  2. Load or create a Workbook class object containing input data for the pivot table
  3. Get the reference to the pivot tables collection in the target worksheet
  4. Add a pivot table in the collection
  5. Configure the newly added pivot table
  6. Add the desired fields into respective areas in the pivot table
  7. Save the output workbook with the pivot table in it

These steps provide instructions for Python code to create pivot table in Excel by sharing a link to the environment configuration resource and to a sequence of tasks to be performed in Python to achieve the functionality. It guides to add fields to different areas in the pivot table as per the requirement. Once the pivot table is prepared, it is saved in the Excel file in the desired format.

Code to Create Excel Pivot Table with Python

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()
These lines of code in Python create Excel pivot table using the data in the loaded Excel file. Note that you can skip the creation of the workbook if you have already an Excel file containing the data and just load it. This code also demonstrates the customization of the newly created pivot table by hiding the grand total of individual rows by setting the RowGrand flag to False whereas you can do other customizations also like setting the title of the alter text, setting column grand, custom list sorting, etc.

This article has guided us to create a pivot table. If you want to read password-protected Excel files, refer to the article on read password protected Excel file in Python.

 English