Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

python - Can I insert matplotlib graphs into Excel programmatically?

I am saving matplotlib files as .tiff images. I'd like to be able to then open an excel file and paste the image there.

openpyxl doesnot seem to support image embedding. xlwt does but only bmp.

ALternatively if i can programmatically convert tiff to bmp, that might help also.

Ideas on either are welcome.

Similar to

Embed multiple jpeg images into EXCEL programmatically?

However converting from tiff to bmp is acceptable as my volume of graphs is small (approximately 10 per file).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is what I found from two different links on the web, that worked perfectly for me. Matplotlib allows saving png files which is what I make use of here:

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

The image part of the code is from Ene Urans response here http://www.daniweb.com/software-development/python/threads/253957/converting-an-image-file-png-to-a-bitmap-file.

The xlwt is simply form the documentation of xlwt I found at http://www.simplistix.co.uk/presentations/python-excel.pdf.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...