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

发布时间 2023-09-22 12:41:16作者: McDelfino

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