Python使用docxtpl循环生成docx文件时每次输出首条数据如何解决
问题根因
你仅在循环外初始化了一次DocxTemplate对象,第一次调用render()方法后,模板内的{{ name }}占位符已经被替换为第一个字典的John值,后续迭代时模板里已经没有可替换的占位符了,所以所有生成的文档都会保留第一次替换的结果。
修复方案
- 把
DocxTemplate实例化逻辑移入for循环内部,每次生成都重新加载原始模板文件,保证每次替换都是基于未修改的原始模板执行 - 不要使用
list作为变量名,这是Python内置类型的关键字,重写会引发潜在的语法冲突
修正后代码
from docxtpl import DocxTemplate from docx2pdf import convert # 重命名变量避免和内置关键字冲突 context_list = [{'name': 'John'}, {'name': 'Amin'}, {'name': 'Carl'}] for i in range(3): # 每次循环重新加载原始模板 doc = DocxTemplate('Hello.docx') doc.render(context_list[i]) doc.save(f'test{i}.docx')
更简洁的优化写法(可选)
直接遍历上下文列表,不用手动控制索引:
from docxtpl import DocxTemplate from docx2pdf import convert context_list = [{'name': 'John'}, {'name': 'Amin'}, {'name': 'Carl'}] for index, context in enumerate(context_list): doc = DocxTemplate('Hello.docx') doc.render(context) doc.save(f'test{index}.docx')
内容的提问来源于stack exchange,提问作者Aminem666
相关产品推荐
相关产品推荐

