pythonms-worddocxtpl

Generate table rows in Word document


I have a Word document template with a table. I want to generate the table rows from my python structure like below.

from docxtpl import DocxTemplate

doc = DocxTemplate("template2.docx") 

context = {
    "topic": "Volcanoes",
    "lessons": [
        {"title": "Introduction to Volcanoes", "objective": "Understand basic concepts of volcanoes"},
        {"title": "Eruption Types", "objective": "Differentiate between types of volcanic eruptions"},
        {"title": "Volcano Case Studies", "objective": "Analyze real-world examples of eruptions"},
        {"title": "Lava and Ash", "objective": "Understand the geological impact of lava and ash"},
    ]
}

doc.render(context)

doc.save("filled.docx")

My Word document template:

enter image description here

When I run the code python3 gen.py I get the following output Word document:

enter image description here

As you can see, it did generate the rows, but the problem is the set of tables/cells it has inserted at the bottom. How can I avoid creating those extra cells/tables?


Solution

  • Just change the last line of your template2.docx, add an tr at the beginning:
    enter image description here