用于刷新单个excel工作表中的连接的Python代码

用于刷新单个excel工作表中的连接的Python代码,python,excel,win32com,vba,Python,Excel,Win32com,Vba,我是python的初学者。我在excel中编写了几个DBQ语句来获取 生成excel,每当打开excel时都应刷新该excel。在连接属性中提供了正确的设置 Below is my python code for refreshall:- import win32com.client import time xl = win32com.client.DispatchEx("Excel.Application") wb = xl.workbooks.open("D:\\Excel shee

我是python的初学者。我在excel中编写了几个DBQ语句来获取 生成excel,每当打开excel时都应刷新该excel。在连接属性中提供了正确的设置

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()
我在excel文件中有3个工作表,其中有3个不同的连接。我想一个接一个地刷新


有人能帮我用python代码分别刷新连接吗?我将非常感谢您的帮助。

因此,如果您希望逐个刷新它们,而不是wb.Refreshall,则命令如下:

for conn in wb.connections:
    conn.Refresh()
如果要在字典中链接,例如与图纸的连接:

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 
注意:如果一张图纸有多个连接,这不是一个好方法

然后,在我的示例中,如果只想更新特定图纸上的一个连接,则称为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() 
最后,如果您直接知道要更新的连接的名称(比如connection_Raj),只需输入:

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

我希望它很清楚,即使它不能完全回答您的问题,因为我不确定我是否理解您想要做什么。

刷新是什么意思?您的意思是文件经常更新吗?是的,手动打开excel时会更新文件。所以我需要一些python代码,可以根据excel文件中的表格进行刷新。