How to use Worksheet.PivotTableWizard in the xlwings API way
The PivotTableWizard method in Excel’s object model is a legacy but powerful tool for programmatically creating pivot tables. In xlwings, this functionality is accessed through the api property, which provides direct access to the underlying Excel object model. The PivotTableWizard method belongs to the Worksheet object and allows for the dynamic generation of pivot tables based on specified source data and parameters. It is particularly useful when you need to automate the creation of pivot tables with custom configurations that might be cumbersome to set up manually through the Excel interface.
The syntax for calling PivotTableWizard via xlwings is as follows:worksheet.api.PivotTableWizard(SourceType, SourceData, TableDestination, TableName, RowGrand, ColumnGrand, SaveData, HasAutoFormat, AutoPage, Reserved, BackgroundQuery, OptimizeCache, PageFieldOrder, PageFieldWrapCount, ReadData, Connection)
Here, worksheet is an xlwings Sheet object. The parameters control various aspects of the pivot table creation. Key parameters include:
SourceType: Specifies the source of data. It can bexlDatabase(Excel range),xlExternal(external data source),xlConsolidation(multiple ranges), orxlScenario. Commonly,xlDatabaseis used.SourceData: The range containing the source data. This can be aRangeobject or a string address.TableDestination: ARangeobject specifying the top-left cell where the pivot table should be placed.TableName: A string for the pivot table’s name.
Other parameters likeRowGrandandColumnGrandcontrol the display of grand totals, whileSaveDatadetermines if data is saved with the pivot table. Many parameters are optional and can be omitted by usingNonein Python.
For example, consider creating a pivot table from data in Sheet1 ranging from A1 to D100, placing the pivot table in Sheet2 starting at cell A3. The following xlwings code demonstrates this:
import xlwings as xw
from xlwings.constants import PivotTableSourceType
# Connect to the active workbook
wb = xw.Book.active
source_sheet = wb.sheets['Sheet1']
destination_sheet = wb.sheets['Sheet2']
# Define source data range
source_range = source_sheet.range('A1:D100')
# Create the pivot table
destination_sheet.api.PivotTableWizard(
SourceType=PivotTableSourceType.xlDatabase,
SourceData=source_range.api,
TableDestination=destination_sheet.range('A3').api,
TableName='SalesPivotTable',
RowGrand=True,
ColumnGrand=True
)