使用pywin32创建Excel数据透视表时遇xlPageField属性错误求助
问题
日常需大量处理Excel工作,计划从VBA迁移至Python。使用pywin32创建数据透视表时,调用win32com.client.constants中的xlPageField、xlRowField、xlColumnField常量时触发AttributeError错误。
相关代码
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
解决方案
方法1:直接使用常量对应数值
Excel的透视字段常量对应固定数值,可直接替换使用:
xlPageField→ 2(筛选字段)xlRowField→ 1(行字段)xlColumnField→ 3(列字段)xlSum→ -4157(求和汇总方式)
修改循环代码:
for field_list, field_r in ((pt_filters, 2), (pt_rows, 1), (pt_cols, 3)): 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
同时修正pt_fields参数格式(原格式不匹配AddDataField要求):
pt_fields = [('Schedule Quantity', '总计划数量', -4157, '#,##0')]
方法2:加载Excel类型库获取常量
用win32com.client.gencache.EnsureDispatch替代Dispatch,它会自动生成Excel类型库,让常量可正常调用:
# 替换原Dispatch代码 xl = win32.gencache.EnsureDispatch('Excel.Application') # 正确获取常量 win32c = xl.constants
之后可正常使用win32c.xlPageField等常量,同时修正pt_fields:
pt_fields = [('Schedule Quantity', '总计划数量', win32c.xlSum, '#,##0')]
方法3:手动生成类型库
若EnsureDispatch无效,可手动生成Excel类型库:
- 打开命令提示符,运行:
python -m win32com.client.makepy "Microsoft Excel xx.x Object Library"
(替换xx.x为你的Excel版本,如2019对应16.0)
2. 重新运行代码即可正常访问win32com.client.constants中的Excel常量。
内容的提问来源于stack exchange,提问作者Connor38
相关产品推荐
相关产品推荐

