我如何使Excel的RefreshAll等待closures,直到完成?

我正在尝试使用以下Python脚本来刷新Excel文件:

xl = Dispatch('Excel.Application') workbook = xl.Workbooks.open('\\path\to\workbook.xlsx') xl.Visible = True workbook.RefreshAll() xl.Quit() 

但是,后台查询(连接到SQL数据库)需要一段时间才能刷新。

在RefreshAll完成之前,如何防止此电子表格closures?

对于'查询'和数据透视表,你可以这样做你必须遍历每个表和查询/透视表*设置后台刷新为False,因为它是表本身的属性(而不是在工作簿级别,比如说。 )

**对于数据透视表,Python模块中的数据透视表似乎不是可迭代的,所以相反,我基本上设置了一个计数器(根据需要调整)来查看每个工作表的最大(期望!)数据透视表它到5)。 如果索引编号从1到5没有find数据透视表,则停止。(假设索引从1开始连续上升,并且不能说没有数据透视表(1),但是有一个数据透视表(2)如果这是错误的,请纠正我的答案!

 for sheet in workbook.Sheets: print(sheet.name) for table in sheet.QueryTables: print("Found a query table on %s called %s" % (sheet.name, table.name)) table.BackgroundQuery = False # ie: disable background query, and therefore cause Excel to 'wait' until it's done refreshing if table.Refresh() == True: # This both refreshes the table, AND if the Refresh() method returns True (ie: refreshes successfully), tells you so. print("Query table %s refreshed!" % table.name) else: print("Query table %s FAILED to refresh." % table.name) for i in range(1,5): try: print("Found pivot table #%s called %s" % (i,sheet.PivotTables(i).Name)) if sheet.PivotTables(i).RefreshTable()==True: print("Refreshed pivot table %s" % sheet.PivotTables(i).Name) else: print("FAILED to refresh pivot table %s" % sheet.PivotTables(i).Name) except: print("No pivot table #%s found on sheet %s" % (i,sheet.Name)) break # Break out of the for loop, since there's no point in continuing the search for pivots, I believe (but could be wrong about that! Try creating two pivots, then deleting the first. Does the second become PivotTables(1), or stay as 2?)