pythondocxtpl

How write to ms word by sample?


I have ms word sample.docx like this:

{{id1}} some text {{name1}} text again {{password1}}

{{id2}} some text {{name2}} text again {{password2}}

{{id3}} some text {{name3}} text again {{password3}}

dict from code

list_data = [
    {"id": "1", "name": "cat", "password": "123"},
    {"id": "2", "name": "john", "password": "321"},
    {"id": "3", "name": "mike", "password": "555"},
    {"id": "1", "name": "who is this", "password": "342"},
    {"id": "2", "name": "some", "password": "67332"},
    {"id": "3", "name": "horse", "password": "qwerty"},
    {"id": "1", "name": "sone n", "password": "some pass n"},
    {"id": "2", "name": "some n", "password": "some pass n"},
    {"id": "3", "name": "some n", "password": "some pass n"},
]

code

from docxtpl import DocxTemplate
context = {}
doc = DocxTemplate("sample.docx")
for i in range(len(list_data)):
    for data in list_data:
        if i % 3 == 0:
            context['id' + data['id']] = data['id']
            context['name' + data['id']] = data['name']
            context['password' + data['id']] = data['password']
            doc.render(context)
            doc.save(f"{i}_output.docx")

this code get next result:

0_output.docx:

1 some text who is this text again 342

2 some text some text again 67332

3 some text horse text again qwerty

and

3_output.docx have result 0_output.docx

--------------------------------------------------------------------------------------------------

How get result

0_output.docx:

1 some cat who is this text again 123

2 some john some text again 321

3 some mike some text again 555

3_output.docx:

1 some text who is this text again 342

2 some text some text again 67332

3 some text horse text again qwerty

etc ....


Solution

  • Try this (Python 3.x):

    from docxtpl import DocxTemplate
    
    list_data = [
        {"id": "1", "name": "cat", "password": "123"},
        {"id": "2", "name": "john", "password": "321"},
        {"id": "3", "name": "mike", "password": "555"},
        {"id": "1", "name": "who is this", "password": "342"},
        {"id": "2", "name": "some", "password": "67332"},
        {"id": "3", "name": "horse", "password": "qwerty"},
        {"id": "1", "name": "sone n", "password": "some pass n"},
        {"id": "2", "name": "some n", "password": "some pass n"},
        {"id": "3", "name": "some n", "password": "some pass n"},
    ]
    
    cols = ['id','name','password']
    
    for i in range(len(list_data)):
        if i % 3 ==0:
            doc = DocxTemplate("sample.docx")
            context = {}
            for col in cols:
                context[f'{col}1'] = list_data[i][col]
                context[f'{col}2'] = list_data[i+1][col]
                context[f'{col}3'] = list_data[i+2][col]
            doc.render(context)
            doc.save(f"{i}_output.docx")