我可以以编程方式将matplotlib图表插入到Excel中吗?

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

openpyxl似乎不支持图像embedded。 xlwt不过只是bmp。

另外,如果我可以编程将tiff转换为bmp,那也可以帮助。

任何想法都是受欢迎的。

如同

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

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

这是我从网上的两个不同的链接中find的,这对我来说是完美的。 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.pdffind的xlwt的文档。

Openpyxl实际上支持图像embedded,对于那些使用.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')