Note that there are some explanatory texts on larger screens.

plurals
  1. POPython: Refresh PivotTables in worksheet
    primarykey
    data
    text
    <p>I'm building a python script that will allow me to open a Excel 2010 worksheet and print it out.</p> <p>I got most of the way</p> <pre><code>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) </code></pre> <p>As you can see I'm still missing the refreshing of the pivot tables in the worksheet.</p> <p>The VBA code for refreshing is:</p> <pre><code>ActiveSheet.PivotTables(1).PivotCache.Refresh </code></pre> <p>I can't seem to break the code into python win32com syntax. The closest I got is:</p> <pre><code>wb.WorkSheets(5).PivotTables(1).PivotCache.Refresh </code></pre> <p>which gives <code>&lt;bound method CDispatch.Refresh of &lt;COMObject PivotCache&gt;&gt;</code> but no result in the the worksheet.</p> <p>Any help would be highly appreciated! </p> <h2>SOLUTION</h2> <p>I ended up finding the solution myself, but gonna keep the post so it can help all programmers with a similar problem.</p> <pre><code>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) </code></pre> <p>Don't forget to vote up if you like or used the code.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload