Using openpyxl to refresh pivot tables in Excle

元气小坏坏 提交于 2019-12-10 17:32:55

问题


I have a file that has several tabs that have pivot tables that are based on one data tab. I am able to write the data to the data tab without issue, but I can't figure out how to get all of the tabs with pivot tables to refresh.

If this can be accomplished with openpyxl that would be ideal.


回答1:


I have similar problem but i thinking that this is thing very particularity of Excel, then, i have two solutions:

Firts, mark the pivottables for that updating when open file excel, for example: right click on pivot table, then, "Options of Pivot table", then, section "Data", then, mark checkbox "Update when on open file"

Second, create one macro for that update all sheets with pivot table, for example:

Dim Hoja As Worksheet
Dim TD As PivotTable
'
'read each sheet of file
For Each Hoja In ActiveWorkbook.Sheets
    'read each pivot table of each sheet
    For Each TD In Hoja.PivotTables
        'update pivot tble
        TD.RefreshTable
    Next TD
Next Hoja



回答2:


If the data source range is always the same, you can set each pivot table as "refresh when open". To do that, just go to the pivot table tab, click on the pivot table, under "Analyze" - > Options -> Options -> Data -> select "Refresh data when opening the file".

If the data source range is dynamic, you can set a named range, and in the pivot table tab, Change Data Source to the named range. And again set "refresh when open".

So the above is achieved without using any python package, alternatively you can use openpyxl to refresh. However make sure that you're using the 2.5 release or above, because otherwise the pivot table format will be lost.




回答3:


Currently what I do is in my template I create a dynamic data range that gets the data from the raw data sheet and then I set that named range to the tables data source. Then in the pivot table options there is a "refresh on open" parameter and I enable that. When the excel file opens it refreshes and you can see it refresh. Currently looking for a way to do it in openpyxl but this is where im at



来源:https://stackoverflow.com/questions/48016206/using-openpyxl-to-refresh-pivot-tables-in-excle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!