Python 如何使Excel刷新等待关闭直到完成?
我正在尝试使用以下Python脚本刷新Excel文件:Python 如何使Excel刷新等待关闭直到完成?,python,sql,excel,refresh,pywin32,Python,Sql,Excel,Refresh,Pywin32,我正在尝试使用以下Python脚本刷新Excel文件: xl = Dispatch('Excel.Application') workbook = xl.Workbooks.open('\\path\to\workbook.xlsx') xl.Visible = True workbook.RefreshAll() xl.Quit() 但是,后台查询(连接到SQL数据库)需要一段时间才能刷新 如何防止此电子表格在RefreshAll完成之前关闭?对于“查询”和透视表,您可以执行此操作。您必须遍
xl = Dispatch('Excel.Application')
workbook = xl.Workbooks.open('\\path\to\workbook.xlsx')
xl.Visible = True
workbook.RefreshAll()
xl.Quit()
但是,后台查询(连接到SQL数据库)需要一段时间才能刷新
如何防止此电子表格在RefreshAll完成之前关闭?对于“查询”和透视表,您可以执行此操作。您必须遍历每个工作表和查询/透视**表,以将后台刷新设置为False,因为它是表本身的属性(而不是工作簿级别的属性) **对于数据透视表,Python模块中的数据透视表似乎不可编辑,因此我基本上设置了一个计数器(根据需要进行调整),以查看每个工作表的最大(预期!)数据透视表数(我将其设置为5)。一旦找到索引号为1到5的数据透视表,则停止此操作。(这假设索引从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 # i.e.: 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 (i.e.: 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?)
CalculateUntilAsyncQueriesDone()将保留程序并等待刷新完成
xl = Dispatch('Excel.Application')
workbook = xl.Workbooks.open('\\path\to\workbook.xlsx')
xl.Visible = True
workbook.RefreshAll()
xl.CalculateUntilAsyncQueriesDone()
xl.Quit()
我认为这是重复的:注意:我还没有想出如何禁用透视表的后台查询刷新…不确定这是否会对您造成问题。目前这不是问题,因为我不需要透视表(至少现在).我肯定最终会调查的。再次感谢!如果我这么做,我会试试你的透视表建议,看看效果如何!