使用python包docx将图直接添加到文档中 [英] Add plots directly to a document using python package docx
问题描述
我正在绘制一些数据,我想自动生成报告.我可以保存该图,然后将其添加到我的文档中.但是,我更喜欢直接执行此操作,而无需节省步骤.我遍历python-docx文档,我怀疑它是否可以通过此软件包使用.还有另一种方法吗?
I am plotting some data and I want to automatically generate a report. I can save the plot and then add it to my document. However, I prefer to do it directly, without saving step. Going through the python-docx documentation I doubt it is doable by this package. Is there another way?
我的代码现在看起来像这样
My code looks like this right now
from docx import Document
from docx.shared import Inches
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)
plt.savefig('test.png')
document = Document()
document.add_heading('Report',0)
document.add_picture('test.png', width=Inches(1.25))
document.save('report.docx')
推荐答案
使用StringIO:
Use StringIO :
此模块实现了类似文件的类StringIO,该类读取并写入一个字符串缓冲区(也称为内存文件).
This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files).
来自docx导入文档的
from docx import Document
from docx.shared import Inches
import matplotlib.pyplot as plt
import numpy as np
from pandas.compat import StringIO
memfile = StringIO()
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)
plt.savefig(memfile)
document = Document()
document.add_heading('Report',0)
document.add_picture(memfile, width=Inches(1.25))
document.save('report.docx')
memfile.close()
Python 3: https://docs.python.org/3/library/io.html
Python 3 : https://docs.python.org/3/library/io.html
Python 2: https://docs.python.org/2/library/stringio.html
Python 2 : https://docs.python.org/2/library/stringio.html
或使用 pandas.compat
这篇关于使用python包docx将图直接添加到文档中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!