Home » excel » Python: Insert object into excel in a specific row and column with win32com

Python: Insert object into excel in a specific row and column with win32com

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m using Python 3.5 and win32com to insert an object (.pdf file) into excel with the following method:

Embedded_object.Add(ClassType=None, Filename=file_loction, Link=False, DisplayAsIcon=True, Left=3, Top=0, Width=50, Height=50)

This works fine, however it always embeds the object in the A1 cell, is there a way to embed the object into a specific row and column using the above method?

Edit:

I also tried the following:

worksheet.Range('A1:A1').Copy()
worksheet.Paste(Destination=worksheet.Range('C2:C2'))

It puts the object in a specific cell, but also what’s behind the object in A1:A1, so it’s not really a solution yet

How to&Answers:

You can specify a destination cell, and then pass those values to the Left and Top properties of the OLEObject like this:

import win32com.client as win32

xl = win32.gencache.EnsureDispatch('Excel.Application')
wb = xl.Workbooks.Open('file_name')
ws = wb.Worksheets("sheet_name")
dest_cell = ws.Range("C2") #change to your wanted location
obj = ws.OLEObjects()
obj.Add(ClassType=None, Filename='file_path', Link=False, DisplayAsIcon=True, Left=dest_cell.Left, Top=dest_cell.Top, Width=50, Height=50)
wb.Save()
xl.Application.Quit()

Answer:

Ok I think I found the solution:

#Create embedded object
Embedded_object = worksheet.OLEObjects()

#Add object to A1:A1 cell
Embedded_object.Add(ClassType=None, Filename=file_loction, Link=False, DisplayAsIcon=True, Left=3, Top=0, Width=50, Height=50)

#Assign object to obj variable
obj = Embedded_object.Item(1)

#Copy and paste object to specific cell
worksheet.OLEObjects(1).Copy()
worksheet.Paste(Destination=worksheet.Range('C2:C2'))

#Delete original object, so only the copied one is left
obj.Delete()