21

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 I'm referring to is here:

Refresh External Data

I'm using Python 2.7 and am relying on Pandas for most of the Excel data parsing.

1
  • And your question is? I can only guess it's "can you refresh the data connections from python" but it's missing from your post. Nov 30, 2016 at 21:47

7 Answers 7

26

CalculateUntilAsyncQueriesDone() will hold the program and wait until the refresh has completed.

xlapp = win32com.client.DispatchEx("Excel.Application")
wb = xlapp.Workbooks.Open(<path_to_excel_workbook>)
wb.RefreshAll()
xlapp.CalculateUntilAsyncQueriesDone()
wb.Save()
xlapp.Quit()
1
  • Can you help me with the code which will work for mac. Jun 20, 2022 at 9:32
18

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(<path_to_excel_workbook>)

# Optional, e.g. if you want to debug
# xlapp.Visible = True

# Refresh all data connections.
wb.RefreshAll()
wb.Save()

# Quit
xlapp.Quit()
6
  • 1
    Thanks for the suggestion - I tried this approach earlier but unfortunately I receive a "This will cancel a pending data refresh. Continue?" dialog box and nothing happens.
    – mk8efz
    Nov 30, 2016 at 23:01
  • Have you tried completing a data refresh from excel, and reboot your computer? This ought to work Nov 30, 2016 at 23:03
  • 3
    Try sleeping for a bit before calling xlapp.Quit(). How long depends on how long the refresh takes to run.
    – cco
    Dec 1, 2016 at 10:42
  • @cco, this is exactly the issue I was having. time.sleep(5) prevented the error. One would expect it to complete the refresh prior to continuing on.
    – Tom
    Aug 31, 2017 at 0:18
  • Internally, Excel can use multiple threads, over multiple processors. If you have a complex spreadsheet, it will even show the number of processors in use when recalculating. IIRC, individual database connections can be synchronously refreshed, but I would assume (and it appears) that`RefreshAll()' runs asynchronously, so the API call will return before the refresh is complete. If the spreadsheet is only used for input, you might consider running the query from Python, since it can talk to any database Excel can.
    – cco
    Aug 31, 2017 at 2:31
6

Adding this as an answer since this is the first Google link - the code in the first answer worked but has incorrect capitalization, it should be:

import win32com.client
import time

xlapp = win32com.client.DispatchEx("Excel.Application")
wb = xlapp.Workbooks.Open(<path_to_excel_workbook>)
wb.RefreshAll()
time.sleep(5)
wb.Save()
xlapp.Quit()
1
  • 1
    Do you really need to wait 5 seconds? Is RefreshAll returning before the refresh has actually completed?
    – gtatr
    Apr 5, 2019 at 10:15
4

A small note, but important one. All the codes above are correct, but it will raise the issue with permission Err 13 because the file is only being saved, not closed as well.

add wb.Close() after save, otherwise the openned Excel will remain in the background app, and if you work with 500 of those, you might get a bit into troubles

3

Adding on top of what everyone else has said, I kept getting the save dialog again when the code got to the Quit line. I set the DisplayAlerts flag to false and it fixed my issue. I didn't need the sleep timer either. This is what worked for me:

xlapp = win32com.client.DispatchEx("Excel.Application")
wb = xlapp.Workbooks.Open(<path_to_excel_workbook>)
wb.RefreshAll()
xlapp.CalculateUntilAsyncQueriesDone()
xlapp.DisplayAlerts = False
wb.Save()
xlapp.Quit()
1

Adding another slightly changed answer as I was stumped by this and none of the solutions were working. What worked for me was enabling Xlsx.DisplayAlerts = True and Xlsx.Visible = True, then at end saving the book with book.Save() and also closing with save: book.Close(SaveChanges=True).

It's a bit cumbersome with Excel opening and closing every time (I am iterating through many excel files), but it works so thats good.

import win32com.client as win32
import pythoncom

def open_close_as_excel(file_path):
    try:
        pythoncom.CoInitialize()
        Xlsx = win32.DispatchEx('Excel.Application')
        Xlsx.DisplayAlerts = True
        Xlsx.Visible = True
        book = Xlsx.Workbooks.Open(file_path)
        book.RefreshAll()
        Xlsx.CalculateUntilAsyncQueriesDone()
        book.Save()
        book.Close(SaveChanges=True)
        Xlsx.Quit()
        pythoncom.CoUninitialize()

        book = None
        Xlsx = None
        del book
        del Xlsx
        print("-- Opened/Closed as Excel --")

    except Exception as e:
        print(e)

    finally:
        # RELEASES RESOURCES
        book = None
        Xlsx = None
4
  • Will the code run without having Excel application ? I am currently trying to solve exact problem but the Virtual machine does not have Excel software. I was trying to do it with Powershell but I don't have sufficient knowledge.
    – Dhiraj D
    Aug 13, 2022 at 15:00
  • 1
    I believe win32 requires the windows application (excel) to be installed on the machine. It uses the app to run
    – henry434
    Aug 14, 2022 at 18:58
  • Is there any way we can run code without Excel application ? I have a requirement to refresh external data in an excel file but we don't have the Excel application.
    – Dhiraj D
    Aug 15, 2022 at 5:37
  • Sorry, you will have to google this.. maybe some solution using excel online, however you'd have to find another package for this as I dont think win32 supports office online
    – henry434
    Aug 17, 2022 at 10:01
0

I am reposting a more complete answer based on the various errors I encountered when I tried existing solutions:

# Open an Instance of Application
xlapp = win32com.client.DispatchEx("Excel.Application") 

# Open File
Workbook = xlapp.Workbooks.Open(<path+file name>) 

# Refresh all  
Workbook.RefreshAll()

# Wait until Refresh is complete
xlapp.CalculateUntilAsyncQueriesDone()

# Save File  
Workbook.Save()

# Quit Instance of Application
xlapp.Quit() 

#Delete Instance of Application
del xlapp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.