简体   繁体   English

使用 xlwings 更改数据透视表的数据源

[英]Change the data source of a pivot table with xlwings

I am currently using the xlwings package to manipulate an excel file.我目前正在使用 xlwings 包来操作 excel 文件。 So far, this package is fantastic, but I do not find a lot of specific documentation on how to modify a pivot table.到目前为止,这个包非常棒,但我没有找到很多关于如何修改数据透视表的具体文档。 My main question is how can I change the data source for a specific pivot table?我的主要问题是如何更改特定数据透视表的数据源?

I think this is a general question so I won't provide any kind of code or excel file.我认为这是一个普遍的问题,所以我不会提供任何类型的代码或 excel 文件。

Thank you for the help.感谢您的帮助。

Ok, a friend of mine found this website with an answerhttps://blog.csdn.net/weixin_39906906/article/details/111374735好的,我的一个朋友找到这个网站有答案https://blog.csdn.net/weixin_39906906/article/details/111374735

but since it's in Chinese, I will post the necessary code below.但由于它是中文的,我将在下面发布必要的代码。

I don't understand everything about this answer.我不明白这个答案的一切。 The win32c object is unknown to me and therefore, I am not comfortable in explaining everything. win32c对象对我来说是未知的,因此,我不太愿意解释一切。

import xlwings as xw
import win32com.client as win32
win32c = win32.constants

# open you excel workbook
wb = xw.Book('excel.xlsx')
# select sheet containing the pivot table
sheet_with_pivot_table = wb.sheets['sheet_pivot_table']

# Write the data range as written in the excel app
data_range = 'sheet_with_data!$A$1:$D$4'

# get the pivot table
pivot_table = sheet_with_pivot_table.api.PivotTables('pivot_table_name')
# This applies the new data
pivot_table.ChangePivotCache(wb.api.PivotCaches().Create(SourceType=win32c.xlDatabase, SourceData=data_range, Version=win32c.xlPivotTableVersion12))

Hopefully, this helps someone else.希望这对其他人有所帮助。

See in this example, with the pivotname that you can change.请参阅此示例,使用您可以更改的pivotname

import xlwings as xw
app_excel = xw.App(visible = False)
wbook = xw.Book( 'Excelfile.xlsx' )
wbook.sheets['datatab'].select()
wbook.api.ActiveSheet.PivotTables('pivotname').PivotCache().refresh()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM