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

99封情书 提交于 2020-12-13 05:10:06

问题


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


回答1:


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()



回答2:


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()


来源:https://stackoverflow.com/questions/50409440/python-insert-object-into-excel-in-a-specific-row-and-column-with-win32com

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!