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

问题描述 投票:0回答:3

我正在绘制一些数据,我想自动生成报告。我可以保存该图,然后将其添加到我的文档中。但是,我更喜欢直接执行,而不保存步骤。浏览 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')
python matplotlib docx python-docx
3个回答
6
投票

尝试在 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()

3
投票

使用 StringIO :

该模块实现了一个类似文件的类 StringIO,它可以读取和 写入字符串缓冲区(也称为内存文件)。

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

0
投票

您可以使用

docxtpl
并使用
jinja
模板来放置图表。

© www.soinside.com 2019 - 2024. All rights reserved.