在openpyx中插入图像

2024-04-19 05:47:52 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

下面将在单元格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')

结果:

enter image description here

在当前版本的openpyxl(至少2.4.5版本)中,您必须这样调用图像:

img = openpyxl.drawing.image.Image('test.jpg')

以Anthon为例:

import openpyxl

wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.image.Image('test.jpg')
img.anchor(ws.cell('A1'))
ws.add_image(img)
wb.save('out.xlsx')

相关问题 更多 >