Python code to refresh the connection in individual excel sheet

假装没事ソ 提交于 2020-06-17 14:37:12

问题


I am a beginner in python. I have written few DBQ statements in excel to fetch result in excel which should be refreshed whenever the excel is opened. Have given the correct setting in connection properties.

Below is my python code for refreshall:- 

import win32com.client  
import time
xl = win32com.client.DispatchEx("Excel.Application")
wb = xl.workbooks.open("D:\\Excel sheets\\Test_consolidation.xlsx")
xl.Visible = True
time.sleep(10)
wb.Refreshall()

I have 3 sheets in the excel file, which has 3 different connections. I want to refresh one after the other.

Can someone help me with the python code to refresh the connections individually ? I would be really grateful for your help.


回答1:


So if you want to refresh all of them but one after the other, instead of wb.Refreshall(), the command would be:

for conn in wb.connections:
    conn.Refresh()

If you want to link (in a dictionary for example) a connection to a sheet:

dict_conn_sheet = {} # create a new dict
for conn in wb.connections: # iterate over each connection in your excel file
    name_conn = conn.Name # get the name of the connection
    sheet_conn = conn.Ranges(1).Parent.Name # get the name of the sheet linked to this connection
    # add a key (the name of the sheet) and the value (the name of the connection) into the dictionary
    dict_conn_sheet[sheet_conn] = name_conn 

Note: if one sheet has more than one connection, this is not a good way.

Then, if you want to update only one connection on a specific sheet (in my example it is called Sheet1):

sheet_name = 'Sheet1'
# refresh the connection linked to the sheet_name 
# if existing in the dictionnary dict_conn_sheet
wb.connections(dict_conn_sheet[sheet_name]).Refresh() 

Finally, if you know directly the name of the connection you want to update (let's say connection_Raj), just enter:

name_conn = 'connection_Raj'
wb.connections(name_conn).Refresh()

I hope it's clear even if it does not answer exactly to your question as I'm not sure I understood what you want to do.



来源:https://stackoverflow.com/questions/47719585/python-code-to-refresh-the-connection-in-individual-excel-sheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!