【问题标题】:How can I collapse or expand a pivot table in python using win32com如何使用 win32com 在 python 中折叠或展开数据透视表
【发布时间】:2022-11-19 19:33:14
【问题描述】:

我正在使用 win32com.client 模块创建数据透视表。 我设法完全按照我的意愿创建它, 但我需要的最后润色是折叠整个数据透视表。

有什么建议么?

这是我的代码:

**
def insert_pt_field_set(pt):
    field_rows = {}
    field_rows['Period'] = pt.PivotFields('Period')
    field_rows['Name'] = pt.PivotFields('Name')

    field_values = {}
    field_values['Name'] = pt.PivotFields("Name")

    field_rows['Period'].Orientation = 1
    field_rows['Period'].Position = 1

    field_rows['Name'].Orientation = 1
    field_rows['Name'].Position = 2


    field_values['Name'].Orientation = 4
    field_values['Name'].Function = -4112


xlApp = win32.Dispatch('Excel.Application')
xlApp.Visible = True
wb = xlApp.Workbooks.Open('output.xlsx')
ws = wb.Worksheets('Sheet1')
ws_pivot = wb.Worksheets('Pivot_Sheet1')

pt_cache = wb.PivotCaches().Create(1, ws.Range("A1").CurrentRegion)
pt = pt_cache.CreatePivotTable(ws_pivot.Range("B3"), "PivotName")

pt.ColumnGrand = True
pt.RowGrand = False

pt.SubtotalLocation(2)
pt.RowAxisLayout(2)

pt.TableStyle2 = "PivotStyleMedium2"

# Entering the function that arrange the fields in the pivot table
insert_pt_field_set(pt)
wb.Close(True)

**

【问题讨论】:

    标签: python excel pivot win32com


    【解决方案1】:

    在 Excel 365 中工作

    如果你需要翻场:

    ws.PivotTables("PivotName").PivotFields("SomeFiled").DrillTo("SomeFiled")
    

    或者

    ws.PivotTables("PivotName").PivotFields("SomeFiled").ShowDetail = False
    

    如果您只想隐藏字段:

    ws.Columns('A:B').OutlineLevel = 2
    ws.Columns('A:B').EntireColumn.Hidden = True
    

    类似问题 VBA Pivot Table Collapse all fields

    它说最好使用“DrillTo”。也许

    更多信息在这里 https://learn.microsoft.com/en-us/office/vba/api/excel.pivotfield.drillto

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2018-12-27
      • 2018-03-18
      • 2022-11-14
      • 1970-01-01
      • 2018-03-06
      相关资源
      最近更新 更多