excel 如何使用win32com在python中折叠或展开数据透视表

w46czmvw  于 2022-11-26  发布在  Python
关注(0)|答案(1)|浏览(251)

我正在使用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)

**

roejwanj

roejwanj1#

使用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

相关问题