pythondocxpython-docxdocxtpl

How can i create table using Docxptl in Python?


I want to create a table using docxtpl in python, where the table rows should be dynamic

For eg:

user_dict = [{"name": "Person 1", "age": 25, "job": "Software Engineer"},
         {"name": "Person 1", "age": 25, "job": "Software Engineer"},
         {"name": "Person 1", "age": 25, "job": "Software Engineer"},
         {"name": "Person 1", "age": 25, "job": "Software Engineer"}]

if the length of list is n table should dynamically populate


Solution

  • I got the output after I was going through the documentation of Docxtpl and tried using list of dictionary

    To create a table with Docxtpl in python

    Sample jinja template format

        from docxtpl import DocxTemplate
    
    user_dict = [{"name": "Person 1", "age": 25, "job": "Software Engineer"},
                 {"name": "Person 1", "age": 25, "job": "Software Engineer"},
                 {"name": "Person 1", "age": 25, "job": "Software Engineer"},
                 {"name": "Person 1", "age": 25, "job": "Software Engineer"}]
    
    doc = DocxTemplate("dynamic_table_tpl.docx")
    context = {'user_record': user_dict}
    context.update(context)
    doc.render(context)
    doc.save(f"user.docx")
    

    Out of the above program

    #python #docxtpl