How Can I Write Charts to Python DocX Document

15k views Asked by At

python beginner here with a simple question. Been using Python-Docx to generate some reports in word from Python data (generated from excel sheets). So far so good, but would like to add a couple of charts to the word document based on the data in question. I've looked at pandas and matplotlib and all seem like they would work great for what I need (just a few bar charts, nothing crazy). But can anyone tell me if it is possible to create the chart in python and have it output to the word document via docx?

2

There are 2 answers

3
scanny On

The general approach that's currently supported is to export the chart from matplotlib or wherever as an image, and then add the image to the Word document.

While Word allows "MS Office-native" charts to be created and embedded, that functionality is not in python-docx yet.

1
bbartling On

I recently ran into this issue too where I wanted a graph output of Python matplotlib to be written directly into a MS word document using the Python module Docx. The only work around that I know of is saving the matplotlib output in a PNG file to a directory on your PC, and then using docx to insert the same file.

This seems to be working for me:

#use matplotlib to generate graph & save PNG to directory

matplotlibExample.plot()
plt.savefig('/Users/MyPC/Documents/Python/matplotlibExample.png')
plt.show()


#use Docx to insert the PNG and save report

document.add_picture('/Users/MyPC/Documents/Python/matplotlibExample.png')    
document.save('/Users/MyPC/Documents/Python/myReport.docx')