【问题标题】:Win32com python : impossible to access a chart on excelWin32com python:无法访问excel上的图表
【发布时间】:2013-05-18 03:26:57
【问题描述】:

我需要使用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 张工作表,如果正在绘制图表对象,我假设它在工作表上

编辑

奇怪的是,每张表的 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

【问题讨论】:

    标签: python excel python-2.7 win32com vba


    【解决方案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 文件有问题。

    【讨论】:

    • 测试类似的代码,Shapes 对我来说效果很好(但ChartObjects 也是如此)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-23
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多