[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.
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2020-09-22 【480】Keras实操