2014-04-25 33 views
0

我不斷收到錯誤,其中xlCategory,xlValuexlPrimary在我的python腳本中無法識別。錯誤xlPrimary在Python中未定義win32com

我試圖標籤我圖的座標軸,併成功地這樣做昨天與此代碼:

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" 

但是這產生了t他下面的錯誤:

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.

回答

0

定義了常量。但是,只有在爲感興趣的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 

現在使用EnsureDispatchgencache

Portable Python >>> xl=client.gencache.EnsureDispatch('Excel.Application') 
Portable Python >>> client.constants.xlPrimary 
1 
Portable Python >>> 

你只需要使用EnsureDispatch一次,因爲一旦類型庫已創建,即使Dispatch也會加載常量。

如果您因任何原因需要清除緩存,不容易找到,但是您可以刪除gen_py文件夾,其路徑可以從win32com.__gen_path__中找到。