Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a picture into Excel at a specified cell position

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'

like image 255
Zzema Avatar asked Oct 28 '25 17:10

Zzema


1 Answers

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()
like image 190
wkzhu Avatar answered Oct 31 '25 08:10

wkzhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!