How To Refresh a Pivot Table Using xlwings?

Method

def modify_data():

    #Modify data source

    sht_data.range(‘F2′).value=’China’

 

def update():

    #Refresh pivot table

    pvt=sht_pvt.api.PivotTables(‘Pivot’)

    pvt.RefreshTable()

Sample Code

#Refresh Pivot Table

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 modify_data():
    #Modify data source
    sht_data.range('F2').value='China'

def update():
    #Refresh pivot table
    pvt=sht_pvt.api.PivotTables('Pivot')
    pvt.RefreshTable()


create_pivot_table()
modify_data()
update()

#bk.save()
#bk.close()
#app.kill()
Refresh a Pivot Table Using xlwings
March 10, 2026 (0)


Leave a Reply

Your email address will not be published. Required fields are marked *