You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pywin32生成Excel图表时遇AttributeError: xlColumnClustered错误

Flask中使用pywin32生成Excel图表触发AttributeError: xlColumnClustered错误

问题概况

在Flask应用里编写了用pywin32生成Excel图表的代码,调用时出现AttributeError: xlColumnClustered错误。已经清理了temp\1\gen_py目录的缓存,也试过Stack Overflow上的相关解决方案,但问题依旧存在。

相关代码

图表生成函数

def add_chart1(location, sheet, range1, title, left, right, height, width, charttype):
    pythoncom.CoInitialize()
    xl = win32.gencache.EnsureDispatch('Excel.Application')
    xl.Visible = True
    ss = xl.Workbooks.Open("demo.xlsx")
    worksheet = ss.Worksheets.Item(sheet)
    workchart = worksheet.ChartObjects().Add(left, right, height, width).Activate()
    xl.ActiveChart.ChartType = charttype
    xl.ActiveChart.Axes(c.xlValue).HasMajorGridlines = False
    xl.ActiveChart.Axes(c.xlCategory).HasTitle = True 
    xl.ActiveChart.SetSourceData(Source=worksheet.Range(range1))
    #workchart.ChartType = 57 # 3DPie
    xl.ActiveChart.HasTitle = True
    workchart_title = xl.ActiveChart.ChartTitle
    workchart_title.Text = title
    
    xl.ActiveChart.HasLegend = True
    xl.ActiveChart.Legend.LegendEntries(1)
    xl.ActiveChart.Legend.Position = -4107 # Right Position
    
    ss.SaveAs("demo.xlsx")
    ss.Close(False); workbook=None
    xl.Application.Quit()

Flask调用代码

import win32com.client as win32
from win32com.client import constants as c
import pythoncom
from flask import *

app = Flask(__name__)

@app.route('/', methods = ['POST'])
def index():
    add_chart1('demo.xlsx', 'Chart',range1, 'Visualization', 350, 32, 600, 300, c.xlColumnClustered)

报错信息

File "C:\Anaconda3\Lib\site-packages\win32com\client\__init__.py", line 178, in __getattr__
raise AttributeError(a)
AttributeError: xlColumnClustered

解决方法

  • 直接用常量数值替代:xlColumnClustered对应的数值是51,把调用里的c.xlColumnClustered换成51即可。其他图表类型也可以用对应数值(比如3D饼图是57),能直接绕过常量导入的问题。
  • 彻底重建类型库缓存:
    1. 关闭所有Excel进程,确保没有后台运行的Excel实例
    2. 删除C:\Users\<你的用户名>\AppData\Local\Temp\gen_py下的所有文件夹(不止temp\1\gen_py)
    3. 单独运行一段测试代码生成缓存,再启动Flask:
      import win32com.client
      win32com.client.gencache.EnsureDispatch("Excel.Application")
      
  • 通过Excel对象获取常量:不需要导入constants as c,直接在函数里通过xl对象调用常量。比如把c.xlColumnClustered换成xl.xlColumnClustered,c.xlValue换成xl.xlValue,c.xlCategory换成xl.xlCategory,这样能避免常量导入失败的问题。
  • 检查Excel版本:不同Excel版本的常量定义可能有差异,确认本地安装的Excel版本是否和代码适配,若版本不兼容,优先用数值替代常量。

内容的提问来源于stack exchange,提问作者Hello World

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 09:40:24