2013-05-17 137 views
1

的圖表,我需要使用python, 找出如何做到這一點我錄製宏更改Excel圖表的公式,這是我得到了什麼:Win32com蟒蛇:無法訪問Excel的

ActiveSheet.ChartObjects("Graphique 1").Activate 
ActiveChart.Axes(xlCategory).Select 
ActiveSheet.ChartObjects("Graphique 1").Activate 
ActiveChart.SeriesCollection(1).Values = "='Données'!$ET$68:$IJ$68" 
ActiveChart.SeriesCollection(1).XValues = "='Données'!$ET$1:$IJ$1" 

所以我的圖表顯然叫做Graphique 1,根據excel文檔ChartObjects在工作表objet上調用。容易吧?

但似乎沒有任何工作:

from win32com import client 
xl = client.Dispatch("Excel.Application") 
xl.Visible = 1 
workbook = xl.Workbooks.Open(r"D:\some\path\file.xls") 
ws = workbook.Sheets("the sheet") 

#tried but did not work : 
ws.ChartObjects("Graphique 1").Activate = True #Exception occured : no element with this name 
ws.ChartObjects("Graphique 1").Activate = 1 #Exception occured : no element with this name 
ws.ChartObjects(1).Activate = True #Exception occured : no message 
ws.ChartObjects(1).Activate = 1 #Exception occured : no message 
#in case it's 0ed indexed 
ws.ChartObjects(0).Activate = True #Exception occured : no message 
ws.ChartObjects(0).Activate = 1 #Exception occured : no message 
print ws.ChartObjects("Graphique 1").SeriesCollection(1).Values #Exception occured : no element with this name 
print ws.ChartObjects(1).SeriesCollection(1).Values #Exception occured : no message 

任何想法? 謝謝。

PS:我真的不現在很多有關Excel的東西,我有10張,我supose我chartObject是在紙張是它被畫

編輯

古怪的一個ChartObjects數每張紙返回0,它怎麼可能?我可以用我自己的眼睛看到它

>>> for i in range(1,10): 
    ws = workbook.Sheets(i) 
    co = ws.ChartObjects() 
    count = co.Count 
    print count 


0 
0 
0 
0 
0 
0 
0 
0 
0 

回答

1

所有這些事情應該不過的工作,如果.ChartObjects()不起作用也許嘗試.Shapes

import win32com.client as win32com 

xl = win32com.DispatchEx ("Excel.Application") 
xl.Visible = True 

wb = xl.Workbooks.Open(r"C:\Book2.xls") 

print wb.Worksheets(1).Name 
# Selecting ChartObjects on a worksheet 
wb.Worksheets(1).ChartObjects(1).Activate() 
wb.Worksheets(1).ChartObjects(1).Select() 

# Selecting Shapes on a worksheet (which charts are shapes) 
#wb.Worksheets(1).Shapes(1).Activate() # Will not work 
wb.Worksheets(1).Shapes(1).Select() 

# This should loop through all of the shapes 
for shape in wb.Worksheets(1).Shapes: 
    print shape.Name 

# This should loop though all Chart objects 
for chartz in wb.Worksheets(1).ChartObjects(): 
    print chartz.Name # Print the name of the chart 

如果這些不工作,那麼顯然您的Excel文件不不認識任何形狀或圖表。嘗試在該工作簿中創建一個新圖表,然後重新運行這些命令以查看它是否顯示,如果沒有,可能是您的Excel文件存在問題。

+0

測試類似的代碼,'Shapes'對我來說工作得很好(但ChartObjects也是如此)。 – Gaffi