Home » excel » excel – How to add Calculated Member to Pivot Table via Python win32

excel – How to add Calculated Member to Pivot Table via Python win32

Posted by: admin May 14, 2020 Leave a comment


I’m trying to add a calculated column into this pivot table that is being generated via a python script with import win32com.client.

Code is posted below that is generating the pivot table. I’m not sure how to add a column. In VBA it would be wb.PivotTable.CalculatedField.Add but that didn’t work (at least the syntax I tried).

I’m trying to calculate [OoCUnits] / [GrossUnits]

#Make Pivot version with four weeks data
Excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
win32c = win32com.client.constants
wb = Excel.Workbooks.Open(filename)
ws3 = wb.Worksheets('Dataset')

cl1 = ws3.Cells(1,1)
cl2 = ws3.Cells(max_row,max_col)
PivotSourceRange = ws3.Range(cl1,cl2)
wb.Sheets.Add (After=wb.Sheets(3))
ws4 = wb.Worksheets(4)
ws4.Name = 'Pivot'

cl3 = ws4.Cells(4,1)
PivotTargetRange = ws4.Range(cl3,cl3)
PivotTableName = 'OoCPivot'

#Make Pivot Table
PivotCache = wb.PivotCaches().Create(SourceType=win32c.xlDatabase, SourceData=PivotSourceRange, Version=win32c.xlPivotTableVersion14)
PivotTable = PivotCache.CreatePivotTable(TableDestination=PivotTargetRange, TableName=PivotTableName, DefaultVersion=win32c.xlPivotTableVersion14)

PivotTable.PivotFields('Product Name').Orientation = win32c.xlRowField
PivotTable.PivotFields('Product Name').Position = 1
PivotTable.PivotFields('Customer Number').Orientation = win32c.xlPageField
PivotTable.PivotFields('Customer Number').Position = 1
PivotTable.PivotFields('Customer Name').Orientation = win32c.xlPageField
PivotTable.PivotFields('Customer Name').Position = 2
PivotTable.PivotFields('Week Ending Date').Orientation = win32c.xlColumnField
PivotTable.PivotFields('Week Ending Date').Position = 1
DataField = PivotTable.AddDataField(PivotTable.PivotFields('GrossUnits'))
DataField.NumberFormat = '#0.00'
DataField = PivotTable.AddDataField(PivotTable.PivotFields('OoCUnits'))
DataField.NumberFormat = '#0.00'

I’m inserting the values with the DataField. The script is not presenting any issues as is.

EDIT: The exact code I implemented to solve. The last two lines are just formatting. I’m including in case it helps someone else.

CalcField = PivotTable.CalculatedFields().Add('OoC Unit %','= OoCUnits / GrossUnits')
DataField = PivotTable.AddDataField(PivotTable.PivotFields('OoC Unit %'))
DataField.NumberFormat = '#%'
PivotTable.DisplayErrorString = True
How to&Answers:

Actually, the method is PivotTable.CalculatedFields().Add() according to docs. Consider placing below at bottom:

CalcField = PivotTable.CalculatedFields().Add("OC_GrossPct", "= OoCUnits / GrossUnits")

PivotTable.PivotFields("OC_GrossPct").Orientation = win32c.xlDataField