【问题标题】:Python: Refresh PivotTables in worksheet [closed]Python:刷新工作表中的数据透视表 [关闭]
【发布时间】:2013-11-04 14:14:40
【问题描述】:

我正在构建一个 python 脚本,它允许我打开 Excel 2010 工作表并将其打印出来。

我得到了大部分的方式

import win32com.client

office = win32com.client.Dispatch("Excel.Application")
wb = office.Workbooks.Open(r"path\to\excel\file\to\print.xlsm")

count = wb.Sheets.Count
for i in range(count):
    ws = wb.Worksheets[i]

    pivotCount = ws.PivotTables().Count
    for j in range(1, pivotCount+1):
        #TODO code to refresh each pivot table

    ws.PrintOut()
    print "Worksheet: %s - has been sent to the printer" % (ws.Name)

如您所见,我仍然缺少工作表中数据透视表的刷新。

刷新的VBA代码为:

ActiveSheet.PivotTables(1).PivotCache.Refresh

我似乎无法将代码分解为 python win32com 语法。我得到的最接近的是:

wb.WorkSheets(5).PivotTables(1).PivotCache.Refresh

给出<bound method CDispatch.Refresh of <COMObject PivotCache>>,但在工作表中没有结果。

【问题讨论】:

    标签: python excel ms-office excel-2010 win32com


    【解决方案1】:

    我发现了我的问题。我在工作表上有保护。这是解决方案:

    import win32com.client
    
    office = win32com.client.Dispatch("Excel.Application")
    wb = office.Workbooks.Open(r"path\to\excel\file\to\print.xlsm")
    
    count = wb.Sheets.Count
    for i in range(count):
        ws = wb.Worksheets[i]
        ws.Unprotect() # IF protected
    
        pivotCount = ws.PivotTables().Count
        for j in range(1, pivotCount+1):
            ws.PivotTables(j).PivotCache().Refresh()
    
        # Put protection back on
        ws.Protect(DrawingObjects=True, Contents=True, Scenarios=True, AllowUsingPivotTables=True)
    
        ws.PrintOut()
        print "Worksheet: %s - has been sent to the printer" % (ws.Name)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-30
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      • 2013-12-23
      相关资源
      最近更新 更多