2013-03-02 117 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') 
相關問題