如何通过示例写入ms word?

How write to ms word by sample?

我有这样的 ms word sample.docx:

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

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

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

来自代码的字典

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"},
]

代码

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")

此代码得到下一个结果:

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

3_output.docx 有结果 0_output.docx

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

如何得到结果

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

等....

试试这个 (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")