使用python-docx & docxtpl生成Word文档

本文介绍如何使用python-docx和docxtpl库生成Word文档,包括安装方法和具体使用过程,展示了如何在模板中插入变量和图片。

最近需要用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上可以会报错。 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值