我需要使用Python更改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 在工作表对象上被调用。很容易吧?
但是似乎没有任何作用:
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张工作表,我想我的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
最佳答案
所有这些都应该有效,但是,如果 .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 文件可能有问题。
关于python - Win32com python : impossible to access a chart on excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16610531/