我可以通过编程方式将matplotlib图形插入Excel吗?

pyt*_*ist 11 python excel matplotlib

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

openpyxl似乎不支持图像嵌入.xlwt确实只有bmp.

或者,如果我可以通过编程方式将tiff转换为bmp,这也可能有所帮助.

我们欢迎任何一个想法.

相近

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

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

pyt*_*ist 8

这是我从网络上的两个不同链接中找到的,这对我来说非常有效.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')
Run Code Online (Sandbox Code Playgroud)

代码的图像部分来自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的文档.


小智 6

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')
Run Code Online (Sandbox Code Playgroud)