How can I go about creating a worksheet (within an excel workbook) with a pivot table using python libs like pyExcelerator / xlrd? I need to generate a daily report that has a pivot table to summarize data on other sheets. One option would be to have a blank template that I copy and populate with the data. In this case, is there a way to refresh the pivot from code? Any other suggestions?
Please clarify (by editing your question) whether "sheet" is an abbreviation of "spreadsheet" and means a whole XLS file, or whether it's an abbreviation of "worksheet", a component of a "workbook".
If by "pivot table" you mean the Excel mechanism, you are out of luck, because that can be created only by Excel. However if you mean a "cross-tab" that you create your self using Python and an appropriate library, you can do this using the trio of xlrd, xlwt and xlutils.
xlrd you appear to know about.
xlwt is a fork of pyExcelerator with bugs fixed and several enhancements. pyExcelerator appears not to be maintained.
xlutils is a package of utility modules. xlutils.copy can be used to make an xlwt Workbook object from an xlrd Book object, so that you can make changes to the xlwt Workbook and save it to a file.
Here is your one-stop-shop for more info on the three packages, together with a tutorial, and links to a google-group/mailing-list which you can use to get help.
I do not believe you can programatically add a pivot table using xlwt
.
But your second approach (populating a pre-configured workbook) seems reasonable.
You can refresh the pivot table using a VBA macro in the template workbook. To do this automatically, create a WorkBook_Open
event handler.
The VBA code to refresh a pivot table is:
Sheet1.PivotTables(1).PivotCache.Refresh