我做了很多 Excel 工作,并且希望从 VBA 迁移到 Python。我正在尝试创建一个数据透视表并添加必要的数据透视字段。我遵循了此站点中的示例代码,但一直试图让 win32com.client.constants 与 xlPageField 一起使用。
import win32com.client as win32
import sys
import logging
win32c = win32.constants
logging.basicConfig(level=logging.INFO)
loc = "C:/Users/Me/Documents/Test.xlsx"
xl = win32.Dispatch('Excel.Application')
#xl.Visible = True
wb = xl.Workbooks.Open (loc)
rd = wb.Sheets("Raw Data")
def pivot_table(wb: object, ws1: object, pt_ws: object, ws_name: str, pt_name: str, pt_rows: list, pt_cols: list, pt_filters: list, pt_fields: list):
#clear previous pivot tables
try:
pt_ws.PivotTables(1)
except:
pass
else:
pt_ws.PivotTables(1).TableRange2.Clear()
# pivot table location
pt_loc = len(pt_filters) + 2
# grab the pivot table source data
#pc = wb.PivotCaches().Create(SourceType=win32.xlDatabase, SourceData=ws1.UsedRange)
pc = wb.PivotCaches().Create(1, SourceData=ws1.UsedRange)
# create the pivot table object
pc.CreatePivotTable(TableDestination=f'{ws_name}!R{pt_loc}C1', TableName=pt_name)
# selecte the pivot table work sheet and location to create the pivot table
pt_ws.Select()
pt_ws.Cells(pt_loc, 1).Select()
# Sets the rows, columns and filters of the pivot table
for field_list, field_r in ((pt_filters, win32c.xlPageField), (pt_rows, win32c.xlRowField), (pt_cols, win32c.xlColumnField)):
for i, value in enumerate(field_list):
pt_ws.PivotTables(pt_name).PivotFields(value).Orientation = field_r
pt_ws.PivotTables(pt_name).PivotFields(value).Position = i + 1
# Sets the Values of the pivot table
for field in pt_fields:
pt_ws.PivotTables(pt_name).AddDataField(pt_ws.PivotTables(pt_name).PivotFields(field[0]), field[1], field[2]).NumberFormat = field[3]
# Visiblity True or Valse
pt_ws.PivotTables(pt_name).ShowValuesRow = True
pt_ws.PivotTables(pt_name).ColumnGrand = True
ws1 = rd
ws2_name = 'Piv'
ws2 = wb.Sheets('Piv')
pt_name = 'example'
pt_rows = ['End Customer']
pt_cols = ['Stage']
pt_filters = ['Project Status']
pt_fields = ['Schedule Quantity']
pivot_table(wb, ws1, ws2, ws2_name, pt_name, pt_rows, pt_cols, pt_filters, pt_fields)
返回的错误是:
for field_list, field_r in ((pt_filters, win32c.xlPageField), (pt_rows, win32c.xlRowField), (pt_cols, win32c.xlColumnField)):
File "C:\Users\Me\AppData\Local\Programs\Python\Python311\Lib\site-packages\win32com\client\__init__.py", line 232, in __getattr__
raise AttributeError(a)
AttributeError: xlPageField
import win32com.client as win32
替换旧代码! xlApp = win32.Dispatch('Excel.Application')
xlApp = win32.gencache.EnsureDispatch('Excel.Application')