Retrieve Excel Workbook Connection Properties

Question:

I am attempting to grab the “Command Text” from the Connection Property window in an Excel file using python. However, I cannot find the object that contains this information. In the below picture I would like to retrieve the highlighted EXEC sp_FooBar as a string:

enter image description here

I am able to retrieve the Connection names with:

import odbc
import win32com.client
file = r'PATH_TO_FILE'
xl = win32com.client.DispatchEx('Excel.Application')
wb = xl.workbooks.open(file)
for x in wb.connections:
    print(x)

But I’m not sure how to use the <COMObject <unknown>> object further to grab the command text. I’m thinking win32com may have something, but can’t seem to crack the code.

Asked By: MattR

||

Answers:

You can get the CommandText property from a OLEDBConnectioninstance like this:

import odbc
import win32com.client

file = r'PATH_TO_FILE'
xl = win32com.client.DispatchEx('Excel.Application')
wb = xl.workbooks.open(file)
for x in wb.Connections:
    print(x.OLEDBConnection.CommandText)
xl.Application.Quit()
Answered By: drec4s
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.