2013-03-02 116 views
8

我将matplotlib文件保存为.tiff图像。我希望能够打开一个excel文件并粘贴图像。我可以以编程方式将matplotlib图形插入Excel吗?

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

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

任何一个想法都是受欢迎的。

类似于

Embed multiple jpeg images into EXCEL programmatically?

然而从TIFF转换为BMP是可接受的,因为我的图表的体积是小的(大约10%的文件)。

回答

7

下面是我从网上的两个不同链接中找到的,这对我来说非常合适。 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') 

代码的图像部分是从这里http://www.daniweb.com/software-development/python/threads/253957/converting-an-image-file-png-to-a-bitmap-file烯URANS响应。

xlwt只是形成了我在http://www.simplistix.co.uk/presentations/python-excel.pdf发现的xlwt的文档。

1

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

此制定了我:

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') 
相关问题