Refresh Excel External Data with Python

前端 未结 5 1084
北荒
北荒 2020-11-29 08:39

I have an Excel file that I run a Python script on. The Excel file has external data connections that need to be refreshed before the Python script is run. The functionality

5条回答
  •  自闭症患者
    2020-11-29 09:35

    If you're on windows, and I believe you are given the screenshot, you can use the win32com module. It will allow you - from python - to open up Excel, load a workbook, refresh all data connections and then quit. The syntax ends up being pretty close to VBA.

    I suggest you install pypiwin32 via pip (pip install pypiwin32).

    import win32com.client
    
    # Start an instance of Excel
    xlapp = win32com.client.DispatchEx("Excel.Application")
    
    # Open the workbook in said instance of Excel
    wb = xlapp.workbooks.open()
    
    # Optional, e.g. if you want to debug
    # xlapp.Visible = True
    
    # Refresh all data connections.
    wb.RefreshAll()
    wb.Save()
    
    # Quit
    xlapp.Quit()
    

提交回复
热议问题