Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Script to Automate Refreshing an Excel Spreadsheet

Tags:

I would like to automatically refresh my excel file. Currently the code I have is not completely satisfactory because Excel asks me each time to click Cancel or OK. I have two sheets in the Excel file.

Here is the python code:

import win32com.client as win32
Xlsx = win32.DispatchEx('Excel.Application')
Xlsx.DisplayAlerts = True
Xlsx.Visible = True
book = Xlsx.Workbooks.Open('C:/Test_Excel/Essai_1.xlsx')
# Refresh my two sheets
book.RefreshAll()
book.Save()
book.Close()
Xlsx.Quit()
del book
del Xlsx

How to automatically refresh the Excel file without Excel asking me any questions.

Thank you

like image 445
Bak Avatar asked Jul 02 '18 04:07

Bak


People also ask

How do you refresh the Excel by using Python?

First, create an object and open the excel application. Using the object, open the excel file containing the pivot table by providing the source path. RefreshAll() method used on the excel instance refreshes all the data connections.


2 Answers

Try setting Xlsx.DisplayAlerts = True to Xlsx.DisplayAlerts = False, that should do the trick.

like image 114
Nordle Avatar answered Sep 28 '22 18:09

Nordle


refreshall() is an async function so you need to wait for it to finish before you do anything else. you can use Xlsx.CalculateUntilAsyncQueriesDone() to accomplish this.

import win32com.client as win32
Xlsx = win32.DispatchEx('Excel.Application')
Xlsx.DisplayAlerts = True
Xlsx.Visible = True
book = Xlsx.Workbooks.Open('C:/Test_Excel/Essai_1.xlsx')
# Refresh my two sheets
book.RefreshAll()
Xlsx.CalculateUntilAsyncQueriesDone()# this will actually wait for the excel workbook to finish updating
book.Save()
book.Close()
Xlsx.Quit()
del book
del Xlsx
like image 40
Chris J Avatar answered Sep 28 '22 19:09

Chris J