Joh*_*son 7 python excel matplotlib python-docx
python初学者在这里有一个简单的问题。一直在使用 Python-Docx 从 Python 数据(从 Excel 表格生成)生成一些 word 报告。到目前为止一切顺利,但想根据相关数据向 Word 文档添加几个图表。我看过 pandas 和 matplotlib ,似乎它们都可以很好地满足我的需要(只有几个条形图,没什么疯狂的)。但是谁能告诉我是否可以在python中创建图表并通过docx将其输出到word文档?
当前支持的一般方法是将图表从matplotlib任何地方导出为图像,然后将图像添加到 Word 文档中。
虽然 Word 允许创建和嵌入“MS Office 原生”图表,但该功能python-docx尚不可用。
我最近也遇到了这个问题,我希望使用 Python 模块 Docx 将 Python matplotlib 的图形输出直接写入 MS Word 文档。我所知道的唯一解决方法是将 PNG 文件中的 matplotlib 输出保存到 PC 上的目录,然后使用 docx 插入相同的文件。
这似乎对我有用:
#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')
Run Code Online (Sandbox Code Playgroud)