4

I try to use this link with vba code but in Python it doesn't work.

import win32com.client    
Excel = win32com.client.Dispatch("Excel.Application")
wb = Excel.Workbooks.Open(r'C:/Users/Home/Desktop/expdata.xlsx')
wb.Worksheets("Report").Activate # выбор активного листа
sheet = wb.ActiveSheet
obj1=wb.ActiveSheet.Pictures.Insert(r'C:\Users\Home\Desktop\picture.jpg')
obj1.ShapeRange
obj1.ShapeRange.LockAspectRatio = msoTrue
obj1.ShapeRange.Width = 75
obj1.ShapeRange.Height = 100
obj1.Left = xlApp.ActiveSheet.Cells(i, 20).Left
obj1.Top = xlApp.ActiveSheet.Cells(i, 20).Top
obj1.Placement = 1
obj1.PrintObject = True
wb.save
wb.Close
Excel.Quit()

AttributeError Traceback (most recent call last) in () 9 sheet.Cells(20, 20).Select 10 #obj1=sheet.Shapes.AddPicture (r'C:/Users/Home/Desktop/picture.jpg', False, True, 10, 3, 100, 100) ---> 11 obj1=wb.ActiveSheet.Pictures.Insert(r'C:/Users/Home/Desktop/picture.jpg') 12 obj1.ShapeRange 13 obj1.ShapeRange.LockAspectRatio = msoTrue

AttributeError: 'function' object has no attribute 'Insert'

Community
  • 1
  • 1
Zzema
  • 197
  • 1
  • 2
  • 16

2 Answers2

15

Unless you absolutely need to use VBA, this sort of thing can be done thru just Python using xlsxwriter: http://xlsxwriter.readthedocs.io/example_images.html

import xlsxwriter

# Create an new Excel file and add a worksheet.
workbook = xlsxwriter.Workbook('images.xlsx')
worksheet = workbook.add_worksheet()
worksheet.insert_image('B2', 'python.png')
workbook.close()
wkzhu
  • 1,616
  • 13
  • 23
  • I sow this link. But I'd like to use VBA, because xlsxwriter does not provide all the features for editing. Forexample, i need to change dimensions that the picture was in the cell. – Zzema Dec 23 '16 at 07:33
  • And xlsxwriter does not allow append information to an existing file. – Zzema Dec 23 '16 at 09:32
  • 1
    Fair enough - back to vba instead of `Pictures.Insert` try `wb.Shapes.AddPicture(FileName, LinkToFile=False, SaveWithDocument=True, Left, Top, Width, Height)` – wkzhu Dec 23 '16 at 14:00
  • @wkzhu You can do scaling and other adjustments, `worksheet.insert_image('B12', 'python.png', {'x_offset': 15, 'y_offset': 10})` see the link to the documentation. – Muneeb Ahmad Khurram Oct 26 '22 at 18:47
0

I found this code to be working.

import win32com.client    
pic_path=r'file_path.png'
Excel = win32com.client.Dispatch("Excel.Application")
wb = Excel.Workbooks.Open(r'C:/Users/Home/Desktop/expdata.xlsx')
ws =wb.Worksheets("Report")
left=ws.Cells(1,required_coloumn).Left
top=ws.Cells(required_row,1).Top
width=required_width
height=required_height
ws.Shapes.AddPicture(pic_path,LinkToFile=False, SaveWithDocument=True,left, top,width,height)
wb.save()
wb.Close()
Excel.Quit()
  • It's close: `ws.Shapes.AddPicture(picPath,LinkToFile=False, SaveWithDocument=True, Left=left, Top=top, Width=width, Height=height)` https://learn.microsoft.com/en-us/office/vba/api/excel.shapes.addpicture – grantr Feb 17 '22 at 06:17