是否可以使用openpyxl插入图像(jpeg、png等)?
基本上我想放置一个生成的带有图表的图像。
我在文档中没有看到任何内容,这似乎与代码的成熟度相比有点缺乏。
以下内容将在A1单元格中插入一张图片。根据您的需要调整图片位置,或者自行处理PIL图像的创建并将其交给Image()
处理。
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.image.Image('test.jpg')
img.anchor = 'A1'
ws.add_image(img)
wb.save('out.xlsx')
在旧版本的openpyxl中,以下内容有效:
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.Image('test.jpg')
img.anchor(ws.cell('A1'))
ws.add_image(img)
wb.save('out.xlsx')
提供关于如何完成此操作的完整更新。这个解决方案使用 openpyxl 版本 2.4.5。
我将一张图片下载到我的本地目录,打开一个现有的工作簿并插入了该图片后保存。
import openpyxl
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.drawing.image import Image
from openpyxl.utils import coordinate_from_string
openpyxl_version = openpyxl.__version__
print(openpyxl_version) #to see what version I'm running
# downloaded a .png to local directory manually from
# "https://www.python.org/static/opengraph-icon-200x200.png"
#change to the location and name of your image
png_loc = r'c:\users\me\opengraph-icon-200x200.png'
# test.xlsx already exists in my current directory
wb = load_workbook('test.xlsx')
ws = wb.active
my_png = openpyxl.drawing.image.Image(png_loc)
ws.add_image(my_png, 'B3')
wb.save('test.xlsx')
Results:
DeprecationWarning: Call to deprecated function anchor (Anchors can be passed in when an image is added to a worksheet).
有任何解决方法吗? - Imad。
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
ws.merge_cells('A1:A3')
img = openpyxl.drawing.image.Image('image.jpg')
row_number = 1
col_idx = 1
cell = ws.cell(row=row_number, column=col_idx)
ws.add_image(img)
wb.save('output.xlsx')
补充一点,我一直在使用openpyxl==2.5.6(与Python3.65一起),我不得不使用img.anchor('A1')
而不是img.anchor(ws.cell('A1'))
。
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.Image('test.jpg')
img.anchor('A1')
ws.add_image(img)
wb.save('out.xlsx')
openpyxl.drawing.Image
已经迁移到openpyxl.drawing.image.Image
。 - Alex Fortinimg.anchor(ws.cell('A1'))
现在是img.anchor = 'A1'
。 - jonyfries