Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python populate a docx table with DocxTemplate

I read this documentation on python-docx-template but I'm pretty confused on the table section. Let's say I have a docx template called Template.docx. Inside the docx file i have a table that only has headers for it's title.

How can I use python-docx-template to dynamically populate the table (add rows and values)?

like image 846
jim Avatar asked Dec 07 '22 12:12

jim


1 Answers

In general, you unlease the power of jinja2 with python-docx-template.

Filling individual variables

Imagine you make a template.docx file with a table:

**table 1**           **table 2**
{{some_content1}}      {{some_content2}}

Then you can fill it using

from docxtpl import DocxTemplate
import jinja2

doc = DocxTemplate("template.docx")
context = { 'some_content1' : "test", "some_content_2": "other"}  # Where the magic happens
doc.render(context)
doc.save("generated_doc.docx")

If you have the data available as a pd.DataFrame then you can also generate the context dictionary. For example:

import itertools 
context = {}
for row, col in itertools.product(df.index, df.columns):
    context[f'{row}_{col}'] = df.loc[row, col]

Dynamic table

You can also generate tables dynamically, which I guess you maybe don't want to do (if you are talking about specifying "table headers" in the docx). It's worth looking into though. Use this template with this example from the git tests:

from docxtpl import DocxTemplate
tpl = DocxTemplate('templates/dynamic_table_tpl.docx')

context = {
'col_labels' : ['fruit', 'vegetable', 'stone', 'thing'],
'tbl_contents': [
    {'label': 'yellow', 'cols': ['banana', 'capsicum', 'pyrite', 'taxi']},
    {'label': 'red', 'cols': ['apple', 'tomato', 'cinnabar', 'doubledecker']},
    {'label': 'green', 'cols': ['guava', 'cucumber', 'aventurine', 'card']},
    ]
}

tpl.render(context)
tpl.save('output/dynamic_table.docx')
like image 126
Roelant Avatar answered Dec 22 '22 21:12

Roelant