Can I insert matplotlib graphs into Excel programmatically?

Openpyxl actually does support image embedding, and might work better for those using .png or existing .xlsx files! The code below appends an image to cell A1 of input.xlsx and saves the file as 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.Image('myplot.png')
img.anchor(ws.cell('A1'))

ws.add_image(img)
wb.save('output.xlsx')

EDIT 2023: Looks like people are still reading this almost 7 years later! I’ve updated Line 7 in the original code to reflect the update for those copy/pasting.

EDIT June 2020: I’ve been informed openpyxl has changed since time of writing. Line 7 has been changed from:

img = openpyxl.drawing.Image('myplot.png')

img = openpyxl.drawing.image.Image('myplot.png')

There is an extra .image in there now.

Leave a Comment