Python:在工作表中刷新数据透视表
我正在构build一个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)
正如你所看到的,我仍然缺less工作表中数据透视表的刷新。
用于刷新的VBA代码是:
ActiveSheet.PivotTables(1).PivotCache.Refresh
我似乎无法将代码分解成python win32com语法。 我得到的最接近的是:
wb.WorkSheets(5).PivotTables(1).PivotCache.Refresh
它给出了<bound method CDispatch.Refresh of <COMObject PivotCache>>
但在工作表中没有结果。
任何帮助将不胜感激!
解
我最终自己find了解决scheme,但是要保留这个post,这样可以帮助所有程序员解决类似的问题。
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)
如果你喜欢或使用的代码不要忘了投票。
我发现我的问题。 我在工作表上有一个保护…愚蠢的我..