Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Write Charts to Python DocX Document

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?

like image 378
John Rogerson Avatar asked Jan 04 '17 19:01

John Rogerson


2 Answers

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.

like image 163
scanny Avatar answered Nov 15 '22 11:11

scanny


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')
like image 40
bbartling Avatar answered Nov 15 '22 12:11

bbartling