Is there a way to automatically refresh an Excel file using ODBC connection (via python or CMD)?

Question:

There’s this one .xlsm file that i need to refresh, automatically, on a regular basis, with data taken from an AS400 device.

The AS400 device launches a script every N. hours; said script updates a file, which contains the data we need to get to the .xlsm file. When called, Excel’s "Refresh All" function creates an ODBC connection with AS400 and populates the .xlsm file with its data.

At the moment, the refreshing process is only manual, and consists of:

  • opening the file with MS Excel (I’m using Office 365’s version, if it can somehow help)
  • clicking on "Refresh All" (which opens a dialog window asking to insert ODBS credentials)
  • Logging in with AS400 credentials

Doing so, file is updated, but of course it would be much more efficient to have it done automatically.

Is there a way to have a python script connected to ODBC (using libraries like pywin32 or similars), and use said connection to refresh the file without a human input? Or is there a way to bypass the whole refresh thing to do it without inserting the credentials inside the dialog window?

Asked By: fil.

||

Answers:

I eventually found a solution, although it’s not exactly the best solution since it has its limitation, but beside that it works quite well.

Inside the Excel file, I went to the "Connections" tab, opened the affected connection’s Properties>Usage tab and checked the "Refresh data when opening the file" option; then, on the Properties>Definition tab I also checked the "Save password" option.

Note that this could be quite a vulnerability if the machine is accessed by many people and you don’t want your data to be seen, but
this wasn’t my case since the machine isn’t accessible to unauthorized users.

Inside a BAT file, i wrote this script:

START excel.exe "pathtofile.xlsm"
timeout 10
python "[path]save_refreshed_file.py"

What this BAT does is basically, opening the file (so that the connecions update themselves automatically) and calling to a python script that does this:

import xlwings as xw

def saveRefreshedFile():

    wbk = xw.Book("pathtofile.xlsm")

    wbk.save("pathtofile.xlsm")

    wbk.close()

Basically, after the file is opened (and consequently updated) by the BAT, the python script connects to the Excel Workbook via the xlwings library and saves it.

After all this is executed, the file is correctly updated even if there’s not someone that can open the file manually. To have it executed on a regular data, the batch can be put under a Task Scheduler.

It’s kind of a bypass of what I had in mind to solve the problem when I first asked the question a couple months ago, but it worked quite well for me, so here it is. Hope it helps someone else too.

Answered By: fil.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.