Home » excel » Python Excel Chart Type pywintypes.com_error

Python Excel Chart Type pywintypes.com_error

Posted by: admin May 14, 2020 Leave a comment

Questions:

The following snippet of my code works fine. It creates a chart and sets it type to xlLine

chart = ws.Shapes.AddChart().Select()
xl.ActiveChart.ChartType = win32com.client.constants.xlLine
xl.ActiveChart.SetSourceData(Source=ws.Range(range))

However if I run this code

chart = ws.Shapes.AddChart().Select()
xl.ActiveChart.ChartType = win32com.client.constants.xlColumn
xl.ActiveChart.SetSourceData(Source=ws.Range(range))

I get the following error

Traceback (most recent call last):
  File "C:\Users\Simon\workspace\python\pyexcelchart\pyexcelchart.py", line 52, in <module>
    excelChart(workbook=wbk,worksheet="Sheet1",range="A1:B6")
  File "C:\Users\Simon\workspace\python\pyexcelchart\pyexcelchart.py", line 46, in excelChart
    xl.ActiveChart.ChartType = win32com.client.constants.xlColumn
  File "C:\WinPython-32bit-2.7.3.3\python-2.7.3\lib\site-packages\win32com\client\__init__.py", line 512, in __setattr__
    d.__setattr__(attr, value)
  File "C:\WinPython-32bit-2.7.3.3\python-2.7.3\lib\site-packages\win32com\client\__init__.py", line 474, in __setattr__
    self._oleobj_.Invoke(*(args + (value,) + defArgs))
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147467259), None)

I have run makepy.py and generated the Excel COM constants but even I use the numeric types such as ChartType = 3, I get the same error. If I set ChartType = 4 (which is line) it works just fine.

I have noticed that if I set ChartType xlColumn to xlRandomText I get a clean AttributeError: xlRandomText. So it seems that python is fine with xlColumn but is having problems automating excel with anything but xlLine. I wonder if this is a python/Excel 2010 issue? By the way I am using python 2.7 and Excel 2010

How to&Answers:

I don’t know why but xlColumn is not listed as an available chart type here:
http://msdn.microsoft.com/en-us/library/office/bb241008(v=office.12).aspx

However, this may work for you:

xl.ActiveChart.Type = win32com.client.constants.xlColumn