gpt4 book ai didi

python - 使用 python 在单元格 Excel 中填充图像

转载 作者:行者123 更新时间:2023-12-01 01:43:58 25 4
gpt4 key购买 nike

我正在尝试使用 python 的 openpyxl 模块将调整大小的照片添加到 Excel 文件中,我使用以下代码但不起作用...仅从指定单元格添加照片(未调整大小)。

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

我也尝试使用 PIL 打开图像,但是当我想将调整大小的图像作为参数提供时,我遇到了一些错误..

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'

最佳答案

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')
<小时/>

如果您考虑以下因素,这是可行的:

  • 已创建新工作簿;
  • Photo.jpg 在原始文件中被更改;

关于python - 使用 python 在单元格 Excel 中填充图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51591634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com