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?
Asked
Active
Viewed 1.4k times
2 Answers
6
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.

scanny
- 26,423
- 5
- 54
- 80
-
1Any update on ? – keramat Jul 20 '23 at 16:05
-
@scanny I am also interested in this, do you have any update on this? – burki Jul 24 '23 at 22:28
-
There's a [PR](https://github.com/python-openxml/python-docx/pull/392) that tried to use python-pptx charts to create them, but it's a bit old. – benkyou Aug 15 '23 at 08:44
6
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')

bbartling
- 3,288
- 9
- 43
- 88
-
1An io.BytesIO object will work as the "file" too, and avoids the need for filesystem access, like `figure = io.BytesIO(); savefig(figure); figure.seek(0); doc.add_picture(figure)` – scanny Nov 02 '20 at 19:49