Fill a image in a cell excel using python

北慕城南 提交于 2019-12-06 14:21:49

问题


I am trying to add a resized photo into a excel file using openpyxl module for python i am using the following code but didnt work... only adds the photo (not resized) from the specified cell.

import openpyxl
from openpyxl import load_workbook
from openpyxl import Workbook

wb = load_workbook('file.xlsx')
ws = wb.active

img = Image.open('photo.jpg')
nimg = img.resize((140,92))
img=openpyxl.drawing.image.Image('photo.jpg')
ws.add_image(img, 'F2') #where F2 is the cell where i want to add the photo

wb.save('test.xlsx')

I also tried to open the image with PIL but when i want to give the resized image as a parameter i`ve got some errors..

import openpyxl
from PIL import Image
from openpyxl import load_workbook
from openpyxl import Workbook

wb = load_workbook('file.xlsx')
ws = wb.active

img = Image.open('photo.jpg')
nimg = img.resize((140,92))
final=openpyxl.drawing.image.Image(nimg) #i think here i got some errors
ws.add_image(final)
wb.save('test.xlsx')

Traceback (most recent call last): File "C:/Users/uidn4858/Desktop/Task2/sc.py", line 29, in <module> new=openpyxl.drawing.image.Image(nimg, 'F2') File "C:\Python27\lib\site-packages\openpyxl-2.4.9-py2.7.egg\openpyxl\drawing\image.py", line 54, in __init__ self.format = image.format.lower() AttributeError: 'NoneType' object has no attribute 'lower' 

回答1:


import openpyxl
from openpyxl import load_workbook
from openpyxl import Workbook
from PIL import Image

width = 23
height = 23

img = Image.open('photo.jpg')
img = img.resize((width,height),Image.NEAREST)
img.save('photo.jpg')

wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.image.Image('photo.jpg')
ws.add_image(img,'F10')
wb.save('out.xlsx')
print('ready')

This works, if you consider the following:

  • New workbook is created;
  • Photo.jpg is changed in the original file;


来源:https://stackoverflow.com/questions/51591634/fill-a-image-in-a-cell-excel-using-python

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