如何使Excel RefreshAll等到关闭直到完成?

时间:2015-12-15 18:19:16

标签: 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完成之前阻止此电子表格关闭?

2 个答案:

答案 0 :(得分:2)

对于'查询'&枢轴表,你可以这样做你必须遍历每张表& query / pivot ** table将后台刷新设置为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?)

答案 1 :(得分:1)

CalculateUntilAsyncQueriesDone()将保留程序,并等待刷新完成。

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