我在python脚本中无法识别xlCategory,xlValue和xlPrimary的错误.
我试图标记我的图形的轴,并使用此代码成功地执行了此操作:
chart = excel.Charts.Add()
chart.Name = "Chart Title"
chart.ChartType = -4169 #xlXYScatter
chart.SetSourceData(firstSheet.Range("$A:$B"))
series = chart.SeriesCollection(1)
series.Name = "Series Name"
chart.Axes(win32com.client.constants.xlCategory).HasTitle = True
chart.Axes(win32com.client.constants.xlCategory).AxisTitle.Caption = "x Axis"
chart.Axes(win32com.client.constants.xlValue).HasTitle = True
chart.Axes(win32com.client.constants.xlValue).AxisTitle.Caption = "y Axis"
这产生了以下错误:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
startGraphBuild()
File "C:\Python33\InCAS_Study_Analysis\VMDvsMODVMDG.py", line 33, in startGraphBuild
chart.Axes(win32com.client.constants.xlCategory).HasTitle = True
File "C:\Python33\lib\site-packages\win32com\client\__init__.py", line 170, in
__getattr__
raise AttributeError(a)
AttributeError: xlCategory
所以我从这个*问题changing axis labels in excel 2007 charts using python win32com尝试了这个:
pAxis = chart.Axes(AxisGroup = xlPrimary)
xAxis = pAxis(1)
yAxis = pAxis(2)
xAxis.HasTitle = True
yAxis.HasTitle = True
xAxis.AxisTitle.Caption = "VMD"
yAxis.AxisTitle.Caption = "MOD VMD"
但是这产生了以下错误:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
startGraphBuild()
File "C:\Python33\InCAS_Study_Analysis\VMDvsMODVMDG.py", line 37, in startGraphBuild
pAxis = chart.Axes(AxisGroup = xlPrimary)
NameError: global name 'xlPrimary' is not defined
还有其他人经历过这个吗?由于昨天工作,我尝试重新启动所有内容,卸载并重新安装pyWin,但这些都没有用.
我使用的是Python 3.3和Excel 2010.
解决方法:
常量已定义.但是,只有在为感兴趣的COM对象创建COM类型库时才会加载它们.有几种方法可以做到这一点(我对Accessing enumaration constants in Excel COM using Python and win32com的自我回答有一些你会觉得有用的链接).但基本上试试这个:
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win
Type "help", "copyright", "credits" or "license" for more information.
Portable Python >>> import win32com
Portable Python >>> win32com.__gen_path__ # path to COM typelib generated by win32com
'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\gen_py\\2.7'
现在尝试使用Dispatch:
Portable Python >>> from win32com import client
Portable Python >>> xl=client.Dispatch('Excel.Application')
Portable Python >>> client.constants.xlPrimary
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "G:\Portable Python 2.7.5.1\App\lib\site-packages\win32com\client\__init_
__getattr__
raise AttributeError(a)
AttributeError: xlPrimary
现在使用gencache中的EnsureDispatch:
Portable Python >>> xl=client.gencache.EnsureDispatch('Excel.Application')
Portable Python >>> client.constants.xlPrimary
1
Portable Python >>>
您只需要使用EnsureDispatch一次,因为一旦创建了类型库,即使Dispatch也会加载常量.
如果你因任何原因需要清除缓存,不容易找到,但你可以删除gen_py文件夹,它的路径可以在win32com .__ gen_path__中找到.