Method
def ref_pivot_table():
#Pivot table reference
print(sht_pvt.api.PivotTables().Count)
print(sht_pvt.api.PivotTables(1).Name) #Reference by index number
print(sht_pvt.api.PivotTables(‘Pivot’).Name) #Reference by name
Sample Code
#Pivot Table References
import xlwings as xw #Import xlwings
import os #Import os
root = os.getcwd() #Get current path
#Create Excel application window, visible, no workbook added
app=xw.App(visible=True, add_book=False)
#Open data file, writable
bk=app.books.open(fullname=root+r'\Pivot.xlsx',read_only=False)
#Get data source worksheet
sht_data=bk.sheets.active
#Data cell range
rng_data=sht_data.api.Range('A1').CurrentRegion
#Create a new worksheet for the pivot table
sht_pvt=bk.sheets.add()
sht_pvt.name='Pivot Table'
def create_pivot_table():
#Location of data
rng_data=sht_data.api.Range('A1').CurrentRegion
#Location of pivot table
rng_pvt=sht_pvt.api.Range('A1')
#Create pivot table cache
pvc=bk.api.PivotCaches().Create(\
SourceType=xw.constants.PivotTableSourceType.xlDatabase,\
SourceData=rng_data)
#Create pivot table
pvt=pvc.CreatePivotTable(\
TableDestination=rng_pvt,\
TableName='Pivot')
#Set fields
pvt.PivotFields('Category').Orientation=\
xw.constants.PivotFieldOrientation.xlPageField #Page fields
pvt.PivotFields('Category').Position=1
pvt.PivotFields('Product').Orientation=\
xw.constants.PivotFieldOrientation.xlColumnField #Column fields
pvt.PivotFields('Product').Position=1
pvt.PivotFields('Origin').Orientation=\
xw.constants.PivotFieldOrientation.xlRowField #Row fields
pvt.PivotFields('Origin').Position=1
pvt.PivotFields('Amount').Orientation=\
xw.constants.PivotFieldOrientation.xlDataField #Value fields
def ref_pivot_table():
#Pivot table reference
print(sht_pvt.api.PivotTables().Count)
print(sht_pvt.api.PivotTables(1).Name) #Reference by index number
print(sht_pvt.api.PivotTables('Pivot').Name) #Reference by name
create_pivot_table()
ref_pivot_table()
#bk.save()
#bk.close()
#app.kill()

Leave a Reply