Home » excel » Python, Excel, and Charts using win32com

Python, Excel, and Charts using win32com

Posted by: admin April 23, 2020 Leave a comment

Questions:

Python and MS Excel question – using win32com, I’m able to create a chart within Excel but i’m unable to move it within a worksheet. I’ve found code online to generate the chart:

import win32com.client
from win32com.client import constants as c

xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
xl.Visible = True
wb = xl.Workbooks.Add()
ws = xl.ActiveSheet
ws.Range('A1').FormulaR1C1 = 'X'
ws.Range('B1').FormulaR1C1 = 'Y'
ws.Range('A2').FormulaR1C1 = 1
ws.Range('A3').FormulaR1C1 = 2
ws.Range('A4').FormulaR1C1 = 3
ws.Range('B2').FormulaR1C1 = 4
ws.Range('B3').FormulaR1C1 = 5
ws.Range('B4').FormulaR1C1 = 6
#ws.Range('A1:B4').Select()
ch = ws.Shapes.AddChart().Select()
xl.ActiveChart.ChartType = c.xlXYScatterLines
xl.ActiveChart.SetSourceData(Source=ws.Range("A1:B4"))
#ch.Location(10,10) # something like this?

How may I move the chart within the worksheet?
enter image description here

How to&Answers:

You can specify the location at the time of creation of the chart expression.AddChart(Type, Left, Top, Width, Height) see here.

If you don’t want to embed the chart in a worksheet, you can create a chart sheet :

wb.Worksheets.Add(Type:=xlChart)

Caveat : Microsoft.interop.Excel not win32com, but should work.