16

我将 matplotlib 文件保存为 .tiff 图像。我希望能够打开一个 excel 文件并将图像粘贴到那里。

openpyxl 似乎不支持图像嵌入。xlwt 可以,但只有 bmp。

或者,如果我可以以编程方式将 tiff 转换为 bmp,那也可能会有所帮助。

欢迎提出任何想法。

如同

以编程方式将多个 jpeg 图像嵌入到 EXCEL 中?

但是,从 tiff 转换为 bmp 是可以接受的,因为我的图表量很小(每个文件大约 10 个)。

4

3 回答 3

9

这是我从网络上的两个不同链接中找到的,对我来说非常有用。Matplotlib 允许保存我在这里使用的 png 文件:

from PIL import Image

file_in = "image.png"
img = Image.open(file_in)
file_out = 'test1.bmp'
print len(img.split()) # test
if len(img.split()) == 4:
    # prevent IOError: cannot write mode RGBA as BMP
    r, g, b, a = img.split()
    img = Image.merge("RGB", (r, g, b))
    img.save(file_out)
else:
    img.save(file_out)

from xlwt import Workbook
w = Workbook()
ws = w.add_sheet('Image')
ws.insert_bitmap(file_out, 0, 0)
w.save('images.xls')

代码的图像部分来自 Ene Urans 的响应http://www.daniweb.com/software-development/python/threads/253957/converting-an-image-file-png-to-a-bitmap-file

xlwt 只是我在http://www.simplistix.co.uk/presentations/python-excel.pdf找到的 xlwt 的文档。

于 2013-03-02T18:39:27.297 回答
9

Openpyxl 实际上确实支持图像嵌入,并且可能更适合那些使用 .png 或现有 .xlsx 文件的人!下面的代码将图像附加到 input.xlsx 的单元格 A1 并将文件保存为 output.xlsx。

import matplotlib.pyplot as plt
import openpyxl

# Your plot generation code here...
plt.savefig("myplot.png", dpi = 150)

wb = openpyxl.load_workbook('input.xlsx')
ws = wb.active

img = openpyxl.drawing.Image('myplot.png')
img.anchor(ws.cell('A1'))

ws.add_image(img)
wb.save('output.xlsx')

编辑 2020 年 6 月:我被告知 openpyxl 自撰写本文以来发生了变化。第 7 行应该是:

img = openpyxl.drawing.image.Image('myplot.png')

现在那里有一个额外的 .image 。

于 2016-07-07T16:16:48.423 回答
4

这对我有用:

import openpyxl

wb = openpyxl.load_workbook('input.xlsx')
ws = wb.active

img = openpyxl.drawing.image.Image('myplot.png')
ws.add_image(ws.cell('A1'))

ws.save('output.xlsx')
于 2018-03-08T17:11:33.843 回答