在openpyxl中插入图像

时间:2012-06-04 21:58:28

标签: python xlsx openpyxl

是否可以使用openpyxl插入图像(jpeg,png等)?

基本上我想放置一个生成的图像,下面有一个图表。

我没有在文档中看到任何内容,与代码的成熟度相比,这似乎有点缺乏。

5 个答案:

答案 0 :(得分:17)

以下内容在单元格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')

答案 1 :(得分:10)

在当前版本的openpyxl中(至少达到2.4.5)你必须像这样调用Image:

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

使用安森的例子:

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

答案 2 :(得分:5)

提供有关如何执行此操作的完整更新。此解决方案使用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

答案 3 :(得分:1)

此代码对我有用:

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

答案 4 :(得分:0)

只需添加一下,我一直在使用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')