[884] How to generate automated Word documents by Python

发布时间 2023-09-22 12:20:50作者: McDelfino

ref: python-docx

ref: How to Generate Automated Word Documents with Python

ref: Automating Word Documents from Excel Using Python | ‘docxtpl’ Tutorial

ref: docxtpl快速上手使用,数据填入以及循环写入表格

ref: 探究Python中的文档自动化工具——docxtpl

ref: Python 第三方库之 docxtpl (处理word文档)

ref: docxtpl user manual


To install using pip:

pip install docxtpl

Usage:

from docxtpl import DocxTemplate

doc = DocxTemplate("my_word_template.docx")
context = {'company_name': "World company"}
doc.render(context)
doc.save("generated_doc.docx")

Example:

"test.docx"

Hello, my name is {{name}}.
I am {{age}} years old now.
I like playing {{sport_01}}, {{sport_02}}, and {{sport_03}}.

python script

doc = DocxTemplate('test.docx')
context = {'name': 'Alex',
           'age': 24,
           'sport_01': 'badminton',
           'sport_02': 'football',
           'sport_03': 'basketball'}

doc.render(context)
doc.save('test_rendered.docx')

"test_rendered.docx"

Hello, my name is Alex.
I am 24 years old now.
I like playing badminton, football, and basketball.

This implementation can be found in Automating Word Documents from Excel Using Python | ‘docxtpl’ Tutorial.

About the generation of tables, please check my next blog. Cheers.