我将 matplotlib 文件保存为 .tiff 图像。我希望能够打开一个 excel 文件并将图像粘贴到那里。
openpyxl 似乎不支持图像嵌入。xlwt 可以,但只有 bmp。
或者,如果我可以以编程方式将 tiff 转换为 bmp,那也可能会有所帮助。
欢迎提出任何想法。
如同
但是,从 tiff 转换为 bmp 是可以接受的,因为我的图表量很小(每个文件大约 10 个)。
我将 matplotlib 文件保存为 .tiff 图像。我希望能够打开一个 excel 文件并将图像粘贴到那里。
openpyxl 似乎不支持图像嵌入。xlwt 可以,但只有 bmp。
或者,如果我可以以编程方式将 tiff 转换为 bmp,那也可能会有所帮助。
欢迎提出任何想法。
如同
但是,从 tiff 转换为 bmp 是可以接受的,因为我的图表量很小(每个文件大约 10 个)。
这是我从网络上的两个不同链接中找到的,对我来说非常有用。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 的文档。
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 。
这对我有用:
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')