Python:刷新工作表中的数据透视表

12

我正在编写一个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>> 但在工作表中没有结果。

1个回答

2

我找到了问题所在。原来工作表上有保护。下面是解决方法:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接