用python实现一个excel数据透视表

问题描述 投票:0回答:1

几天来,我一直在尝试使用不同的库在我的 Mac 操作系统上实现一个数据透视表,并最终使用了 xlwings,因为它看起来支持它。我主要在 Windows 上看到示例,但在 Mac 上看不到。经过一些研究,我得到了下面的代码,但它在这一行崩溃了

pivot_table = pivot_sheet.api.create_pivot_table(table_destination=pivot_range.api, read_data=data_range.api, table_name='MyPivotTable')
。我是这方面的新手,所以我可能做错了或者使用了错误的 mac 语法。贝娄也是我得到的错误。

我本可以使用 pandas,但保存到 excel 文件时它看起来并不像数据透视表。我需要一个可以让我添加行、列、过滤器和值字段的工具。

这个 github 文件 我发现有 mac os 语法,这与 windows 不同

任何帮助将不胜感激

import xlwings as xw
from xlwings import constants

# Open the workbook
wb = xw.Book('test_excel.xlsx')

# Select the data range
data_range = wb.sheets['Sheet1'].range('A1:C6')

# Create the pivot table
pivot_sheet = wb.sheets.add(name='PivotT')
pivot_range = pivot_sheet.range('A1')

print(pivot_range.api)
print(data_range.api)
pivot_table = pivot_sheet.api.create_pivot_table(table_destination=pivot_range.api, read_data=data_range.api, table_name='MyPivotTable')

# Add the fields

# structure the pivot table
pivot_table.pivot_fields('Name').orientation = constants.PivotFieldOrientation.xlRowField
pivot_table.pivot_fields('Gender').orientation = constants.PivotFieldOrientation.xlPageField
pivot_table.pivot_fields('Age').orientation = constants.PivotFieldOrientation.xlColumnField

DataField = pivot_table.add_data_field(pivot_table.pivot_fields('Age'))
DataField.Function = constants.TotalsCalculation.xlTotalsCalculationSum

# Save and close the workbook
wb.save()
wb.close()
Traceback (most recent call last):
  File "/Users/username/Desktop/pivot table/pt_code.py", line 257, in <module>
    pivot_table = pivot_sheet.api.create_pivot_table(table_destination=pivot_range.api, read_data=data_range.api, table_name='MyPivotTable')
  File "/Users/username/.virtualenvs/pt_python/lib/python3.9/site-packages/aeosa/appscript/reference.py", line 515, in __call__
    raise CommandError(self, (args, kargs), e, self.AS_appdata) from e
appscript.reference.CommandError: Command failed:
        OSERROR: -50
        MESSAGE: Parameter error.
        COMMAND: app(pid=9891).workbooks['test_excel.xlsx'].worksheets['PivotT'].create_pivot_table(table_destination=app(pid=9891).workbooks['test_excel.xlsx'].worksheets['PivotT'].cells['A1'], read_data=app(pid=9891).workbooks['test_excel.xlsx'].worksheets['Sheet1'].cells['A1:C6'], table_name='MyPivotTable')

测试代码

import xlwings as xw
wb = xw.Book('test_pt.xlsx')
app = wb.app
try:
    app.Run('') # not sure of what to put here
    print("here")
except Exception as e:
    print(e)
wb.save()

.bas 文件

Attribute VB_Name = "Module1"
Sub Macro1()

    Range("A1").Select

    Range(Selection, Selection.End(xlToRight)).Select

    Range(Selection, Selection.End(xlDown)).Select

    Application.CutCopyMode = False

    ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$1:$P$30"), , xlYes).Name = _

        "Table1"

    Range("Table1[#All]").Select

    Sheets.Add

    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _

        "Table1", Version:=8).CreatePivotTable TableDestination:="Sheet2!R3C1", _

        TableName:="PivotTable3", DefaultVersion:=8

    Sheets("Sheet2").Select

    Cells(3, 1).Select

    With ActiveSheet.PivotTables("PivotTable3").PivotFields("market")

        .Orientation = xlPageField

        .Position = 1

    End With

    With ActiveSheet.PivotTables("PivotTable3").PivotFields("wallet")

        .Orientation = xlPageField

        .Position = 1

    End With

    With ActiveSheet.PivotTables("PivotTable3").PivotFields("period")

        .Orientation = xlPageField

        .Position = 1

    End With

    With ActiveSheet.PivotTables("PivotTable3").PivotFields("device")

        .Orientation = xlPageField

        .Position = 1

    End With

    With ActiveSheet.PivotTables("PivotTable3").PivotFields("device_model")

        .Orientation = xlPageField

        .Position = 1

    End With

    With ActiveSheet.PivotTables("PivotTable3").PivotFields("device_manufacturer")

        .Orientation = xlPageField

        .Position = 1

    End With

    With ActiveSheet.PivotTables("PivotTable3").PivotFields("card prov")

        .Orientation = xlPageField

        .Position = 1

    End With

    With ActiveSheet.PivotTables("PivotTable3").PivotFields("instant_acc")

        .Orientation = xlPageField

        .Position = 1

    End With

    With ActiveSheet.PivotTables("PivotTable3").PivotFields("Attemps")

        .Orientation = xlRowField

        .Position = 1

    End With

    With ActiveSheet.PivotTables("PivotTable3").PivotFields("in check")

        .Orientation = xlRowField

        .Position = 2

    End With

    With ActiveSheet.PivotTables("PivotTable3").PivotFields("flow")

        .Orientation = xlRowField

        .Position = 3

    End With

    With ActiveSheet.PivotTables("PivotTable3").PivotFields("event reason")

        .Orientation = xlRowField

        .Position = 4

    End With

    With ActiveSheet.PivotTables("PivotTable3").PivotFields("status")

        .Orientation = xlColumnField

        .Position = 1

    End With

    ActiveSheet.PivotTables("PivotTable3").AddDataField ActiveSheet.PivotTables( _

        "PivotTable3").PivotFields("nconv"), "Sum of nconv", xlSum

End Sub
python-3.x excel pivot-table xlwings
1个回答
0
投票

应该能够做类似下面的事情;
这为我运行了宏;
宏在创建 Pivot 缓存时出错,我没有深入研究原因,但工作表已打开,

macro1
保存在
Module1
中开始运行。
另一个注意事项,启用宏的 Excel 书籍需要另存为
.xlsm
所以我希望您打开的文件是
test_pt.xlsm
而不是
test_pt.xlsx
.

import xlwings as xw


path = 'test_pt.xlsm'

with xw.App(visible=True) as app:
    wb = xw.Book(path)
    ExcelMacro = wb.macro('macro1')
    ExcelMacro()
© www.soinside.com 2019 - 2024. All rights reserved.