最近需要用python生成Word文档,期间用到了python-docx 和 docxtpl库,下面梳理一下具体的使用过程。
1、安装方法:
这两者都可以用pip安装
$ pip install python-docx
$ pip install docxtpl
python-docx 相对比较难安装一点,可能会遇到坑,可以参考这篇博客上的方法:在Windows上安装python-doc。
docxtpl 比较好安装,不出意外是一次成功。
2、使用方法:
# coding:utf-8
from docxtpl import DocxTemplate, InlineImage
from docx.shared import Pt
def generate_report(tpl_file, report_file):
tpl = DocxTemplate(tpl_file)
context = {
"year": "2020",
"month": "08",
"day": "30",
"hour": "11",
"minute": "00",
"figure1": InlineImage(tpl, "timg.jpeg", width=Pt(205), height=Pt(185)),
"name": "zhoumin"
}
tpl.render(context)
tpl.save(report_file)
def main():
tpl_file = "template.docx"
report_file = "report.docx"
generate_report(tpl_file, report_file)
if __name__ == "__main__":
main()
模板文档:
生成文档:
3、备注
- 图片居中的方法:在模板中将待替换的内容设为居中样式
- 模板文件名称 和 生成文件名称,最好不要用中文,在Windows上可以会报错。