alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[885] How to generate automated tables in Word document with Python

ref: How to Generate Automated Word Documents with Python

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


Creating a Template

Before you can proceed, you must first create your very own template document that is basically a normal Microsoft Word Document (.docx) formulated exactly the way you want your automated report to be, down to every nitty-gritty detail such as typefaces, font sizes, formatting, and page structure. The only thing you need to do afterward is to create placeholders for your automated content and declare them with variable names as shown below.

image

As you’ve probably promptly guessed, any automated content can be declared inside a set of double curly brackets {{variable_name}}. This includes text and images. For tables, it is a little more complicated. You need to create a table with a template row with all the columns included, and then you need to append one row above and one row below with the following notation:

First row:

{%tr for item in _variable_name_ %}

Last row:

{%tr endfor %}

Please note that in the figure above the variable names are

  • table_contents for the Python dictionary that will store our tabular data
  • Index for the dictionary keys (first column)
  • Value for the dictionary values (second column)

Once done, save your document in your directory as a .docx file and proceed with writing the code to invoke the template and generate an automated document.

Note: for tables, the variables we should change are _variable_name_, item.Index, item.Value. The word "item" needs to be kept unchanged.


Example:

table-template.docx

python script

doc = DocxTemplate('table-template.docx')
company = {
"name": "Plumsail",
"email": "contact@plumsail.com"
}
employees = [
{
"name": "Derek Clark",
"jobTitle": "Marketing director",
"department": "Marketing Department",
"office": "Room 18",
"phone": "(206) 854-9798"
},
{
"name": "Xue Li",
"jobTitle": "Financial director",
"department": "Financial Department",
"office": "Room 19",
"phone": "(206) 598-1259"
},
{
"name": "Jessica Adams",
"jobTitle": "Marketing manager",
"department": "Marketing Department",
"office": "Room 23",
"phone": "(206) 789-1598"
},
{
"name": "Katsuko Kawakami",
"jobTitle": "Analyst",
"department": "Financial Department",
"office": "Room 26",
"phone": "(206) 784-1258"
}
]
context = {}
context['company'] = company
context['employees'] = employees
doc.render(context)
doc.save('table-template_rendered.docx')

table-template_rendered.docx


posted on   McDelfino  阅读(14)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-09-22 【480】Keras实操
点击右上角即可分享
微信分享提示