Search code examples
pythonexcelwin32compolylinesafearray

How to Add polyline in Excel with python win32com.client?


I am trying to Add polyline in excel with python win32com.client

here my code:

import pythoncom

file = r"D:\\shapes.xlsx"
import win32com.client as client
import win32api

xl = client.gencache.EnsureDispatch("Excel.Application")
xl.Visible = True
wb = xl.Workbooks.Open(file)
ws = wb.Sheets(1)
# xl.ActiveWindow.DisplayGridlines = False
print(ws.Cells(11, 2).Left)
fr = ws.Shapes.AddShape(1, ws.Cells(11, 2).Left, ws.Cells(11, 2).Top, 100, 100)
sr = ws.Shapes.AddShape(1, ws.Cells(11, 7).Left, ws.Cells(11, 7).Top, 100, 100)

points= client.VARIANT(pythoncom.VT_ARRAY, (( ws.Cells(11, 2).Left, ws.Cells(11, 2).Top), ( ws.Cells(11, 2).Left, Left, ws.Cells(11, 7).Top), (ws.Cells(11, 7).Left, ws.Cells(11, 7).Top)))
l=ws.Shapes.AddPolyline(points)

it gives error MemoryError: CreatingSafeArray

How to add polyline with python?


Solution

  • This took a fair bit of trial and error. It seems you have to explicitly create a VARIANT for each point. While you might hope that the win32com.VARIANT() function might convert a Python array of arrays ie [[],[],...], it doesn't seem to manage it, or at least doesn't create the type of parameter that Excel is expecting.

    Lifting the co-ordinate example from the Microsoft documentation, and with a hat-tip to @joojaa's SO answer to a similar question:

    import win32com.client as wc
    from pythoncom import VT_VARIANT
    
    xl = wc.gencache.EnsureDispatch('Excel.Application')
    
    xl.Visible=True
    wb = xl.Workbooks.Add()
    
    ws = wb.Worksheets[1]
    
    triangle = [[ 25,100],
                [100,150],
                [150, 50],
                [ 25,100] ]
    
    #Create list of arrays
    points = [wc.VARIANT(VT_VARIANT,pt) for pt in triangle]
    
    #points implicitly converted to VARIANT array
    ws.Shapes.AddPolyline(points)
    

    With this result in Excel:

    enter image description here