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

发布于 2021-01-29 15:26:02

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

任何帮助将不胜感激!

我最终自己找到了解决方案,但要保留这个职位,以便它可以帮助所有遇到类似问题的程序员。

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)

如果您喜欢或使用该代码,请不要忘记投票。

关注者
0
被浏览
163
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    我发现了问题。我在工作表上有一个保护措施…愚蠢的我..



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看