簡體   English   中英

如何使用 win32com 在 python 中折疊或展開 pivot 表

[英]How can I collapse or expand a pivot table in python using win32com

我正在使用 win32com.client 模塊創建一個 pivot 表。 我正在設法完全按照我的意願創建它,但我需要的最后一步是折疊整個 pivot 表。

有什么建議么?

這是我的代碼:

**
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)

**

在 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 表格 收起所有字段

它說最好使用“DrillTo”。 也許

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM