简体   繁体   English

如何在带有 python 的 excel 表中插入一个真正的 pivot 表?

[英]How to insert a real pivot table in a excel sheet with python?

I want to create a "real" pivot table in excel sheet with python without using the function of pandas (pandas.pivot_table).我想用 python 在 excel 工作表中创建一个“真实的”pivot 表,而不使用 pandas (pandas.pivot_table) 的 function。 Is there a method?有方法吗? I need to create the "true" pivot table in excel with a dropdown combo box.我需要使用下拉组合框在 excel 中创建“真实的”pivot 表。 Unfortunately the pandas pivot is static (is a table) and not dynamic.不幸的是 pandas pivot 是 static(是一个表)而不是动态的。 Can anyone help me?谁能帮我?

Can you try it this way?你可以这样试试吗?

import win32com.client
Excel   = win32com.client.gencache.EnsureDispatch('Excel.Application') # Excel = win32com.client.Dispatch('Excel.Application')

win32c = win32com.client.constants

wb = Excel.Workbooks.Add()
Sheet1 = wb.Worksheets("Sheet1")

TestData = [['Country','Name','Gender','Sign','Amount'],
             ['CH','Max' ,'M','Plus',123.4567],
             ['CH','Max' ,'M','Minus',-23.4567],
             ['CH','Max' ,'M','Plus',12.2314],
             ['CH','Max' ,'M','Minus',-2.2314],
             ['CH','Sam' ,'M','Plus',453.7685],
             ['CH','Sam' ,'M','Minus',-53.7685],
             ['CH','Sara','F','Plus',777.666],
             ['CH','Sara','F','Minus',-77.666],
             ['DE','Hans','M','Plus',345.088],
             ['DE','Hans','M','Minus',-45.088],
             ['DE','Paul','M','Plus',222.455],
             ['DE','Paul','M','Minus',-22.455]]

for i, TestDataRow in enumerate(TestData):
    for j, TestDataItem in enumerate(TestDataRow):
        Sheet1.Cells(i+2,j+4).Value = TestDataItem

cl1 = Sheet1.Cells(2,4)
cl2 = Sheet1.Cells(2+len(TestData)-1,4+len(TestData[0])-1)
PivotSourceRange = Sheet1.Range(cl1,cl2)

PivotSourceRange.Select()

Sheet2 = wb.Worksheets(2)
cl3=Sheet2.Cells(4,1)
PivotTargetRange=  Sheet2.Range(cl3,cl3)
PivotTableName = 'ReportPivotTable'

PivotCache = wb.PivotCaches().Create(SourceType=win32c.xlDatabase, SourceData=PivotSourceRange, Version=win32c.xlPivotTableVersion14)

PivotTable = PivotCache.CreatePivotTable(TableDestination=PivotTargetRange, TableName=PivotTableName, DefaultVersion=win32c.xlPivotTableVersion14)

PivotTable.PivotFields('Name').Orientation = win32c.xlRowField
PivotTable.PivotFields('Name').Position = 1
PivotTable.PivotFields('Gender').Orientation = win32c.xlPageField
PivotTable.PivotFields('Gender').Position = 1
PivotTable.PivotFields('Gender').CurrentPage = 'M'
PivotTable.PivotFields('Country').Orientation = win32c.xlColumnField
PivotTable.PivotFields('Country').Position = 1
PivotTable.PivotFields('Country').Subtotals = [False, False, False, False, False, False, False, False, False, False, False, False]
PivotTable.PivotFields('Sign').Orientation = win32c.xlColumnField
PivotTable.PivotFields('Sign').Position = 2

DataField = PivotTable.AddDataField(PivotTable.PivotFields('Amount'))
DataField.NumberFormat = '#\'##0.00'

Excel.Visible = 1

wb.SaveAs('ranges_and_offsets.xlsx')
Excel.Application.Quit()

https://www.yinglinglow.com/blog/2018/04/29/xlwings-pivot-table https://www.yinglinglow.com/blog/2018/04/29/xlwings-pivot-table

Here is another way using xlwings.这是使用 xlwings 的另一种方式。

    import xlwings as xw
    from xlwings import constants

    # create instance of Excel app
    app = xw.App(visible=True)
    
    # create workbook object
    wb = app.books.open('my_file')  # where my_file is in .xlsx format

    # create sheet object
    sht = wb.sheets['my_sheet_name']  # where my_sheet_name is name of your Excel sheet name that contains your data

    # determine last row and column of your data
    num_col = sht.range('A1').end('right').column
    num_row = sht.range('A1').end('down').row

    # define your pivot table data range
    PivotSourceRange = sht.range((1,1), (num_row, num_col))

    # add a pivot sheet to your Excel file
    xw.sheets.add(name='pivot', before='my_sheet_name')

    # name your pivot table
    PivotTableName = 'MyPivotTable'
    pivot_tab_name = '' + 'pivot' + '!R1C1'

    # create pivot table cache
    PivotCache = wb.api.PivotCaches().Create(SourceType=constants.PivotTableSourceType.xlDatabase,
                                     SourceData=PivotSourceRange.api,
                                     Version=constants.PivotTableVersionList.xlPivotTableVersion14)

    PivotTable = PivotCache.CreatePivotTable(TableDestination=pivot_tab_name,
                                     TableName=PivotTableName,
                                     DefaultVersion=constants.PivotTableVersionList.xlPivotTableVersion14)

    # structure the pivot table
    PivotTable.PivotFields('your_row_label').Orientation = constants.PivotFieldOrientation.xlRowField
    PivotTable.PivotFields('your_page_label').Orientation = constants.PivotFieldOrientation.xlPageField

    DataField = PivotTable.AddDataField(PivotTable.PivotFields('the_column_you_want_to_tabulate'))
    DataField.Function = constants.TotalsCalculation.xlTotalsCalculationAverage

    # other available calculation methods include:
    # .xlTotalsCalculationCountNums
    # .xlTotalsCalculationMax
    # .xlTotalsCalculationMin
    # .xlTotalsCalculationNone
    # .xlTotalsCalculationCount
    # .xlTotalsCalculationCustom
    # .xlTotalsCalculationStdDev
    # .xlTotalsCalculationSum
    # .xlTotalsCalculationVar

    # you specify the formatting of your numbers with this statement
    DataField.NumberFormat = '0.0'  # which uses standard Excel formats

    # finish building the pivot table
    PivotTable.PivotFields('your_page_label').EnableMultiplePageItems = True
    PivotTable.PivotFields('your_page_label').PivotItems().Visible = True

End result is something like this:最终结果是这样的:

在 Excel 中创建数据透视表的示例

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

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