使用 python 包 docx 将图表直接添加到文档中

Add plots directly to a document using python package docx

我正在绘制一些数据,我想自动生成一份报告。我可以保存绘图,然后将其添加到我的文档中。但是,我更喜欢直接做,不节省步骤。通过 python-docx 文档,我怀疑这个包是否可行。还有别的办法吗?

我的代码现在看起来像这样

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 :

This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files).

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 2 : https://docs.python.org/2/library/stringio.html

或者使用 pandas.compat

中的 StringIO

尝试下面的代码 python 3 直接将绘图保存在文档中。

from docx import Document
from docx.shared import Inches
import matplotlib.pyplot as plt
import numpy as np
from pandas.compat import BytesIO

memfile = BytesIO()
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()