python-docx-template
python-docx-template copied to clipboard
Docxtpl not rendering
I'm trying to iterate through an excel file, populate a docxtemplate from each row and save the docs. The excel file and the template are in Bulgarian language. I don't believe that's causing the error but I'm new to python, so I appreciate any help.
Reading the excel file is fine. I can display the results.
Below is my code and the error I get:
import pandas as pd import jinja2 from docxtpl import DocxTemplate
word_template_path = r"C:\Users\mdjat\Documents\ZdrDosieta\ZDRPrilojenieTemplate.docx" excel_path = r"C:\Users\mdjat\Documents\ZdrDosieta\ВИА ЛОГИСТИК_информация за ЗД_за тест.xlsm" doc = DocxTemplate (word_template_path) df = pd.read_excel (excel_path,sheet_name="Sheet1")
for index, row in df.iterrows (): context = {'Трите имена': row['Трите имена'], 'ЕГН': row['ЕГН'], 'Постоянен адрес': row['Постоянен адрес'], 'Населено място': row['Населено място'], 'Лекар': row['Лекар'], 'Длъжност': row['Длъжност'], 'Стаж': row['Стаж']} doc.render (context) output_path = r"C:\Users\mdjat\Documents\ZdrDosieta{row['Трите имена']}.docx" doc.save (output_path)
Traceback (most recent call last):
File "c:\Users\mdjat\Documents\ZdrDosieta\zdr dosie python code.py", line 26, in
I've read posts with similar errors but still don't get how to fix it.
Any help or direction would be greatly appreciated.
You are using keys with spaces in your context dictionary. I suspect that this is causing the problem. There are two possible solutions:
Method 1:
Use underscores instead of spaces in your context dictionary:
Python file:
context = {
'Трите_имена': row['Трите имена'],
...
}
docx template:
{{ Трите_имена }}
Method 2:
Keep keys of context dictionary unchanged, but quote them in the docx template:
Python file:
context = {
'Трите имена': row['Трите имена'],
...
}
docx template:
{{ 'Трите_имена' }}