Automate Word Documents From Excel With Python and docxtpl
docxtpl fills a Word template with Python. Type placeholders such as {{ month }} into a normal .docx, read the values from Excel with pandas or xlwings, then call render() and save(). Conditions, table rows and pictures work too, so one script turns a sheet into a finished Word or PDF report.
Table of contents
Install docxtpl
docxtpl is a free Python package that installs with pip. It brings python-docx (which reads and writes .docx files) and Jinja2 (which handles the placeholders) along with it. The examples below also use pandas and matplotlib for the Excel data and the chart.
python -m pip install docxtpl pandas openpyxl matplotlib
Add xlwings pywin32 to that line if you want the Excel button and the PDF export through Word, both covered below. I tested every script on this page with Python 3.12, docxtpl 0.20.2, python-docx 1.2.0 and pandas 3.1.1.
Two install traps come up often. Install the package called docxtpl (the import name is the same), and never pip install docx: that is an old, unrelated package that breaks import docx. And use python -m pip rather than plain pip, so the package lands in the same Python that runs your script.
Build the Word template
A docxtpl template is an ordinary Word document. You design it in Word with your fonts, logos and layout, and type placeholders in double curly braces where the values should go. Python only swaps the placeholders, so everything else stays exactly as you designed it.

-
Design the document in Word. Start from a finished report or a Word template and save it as .docx, not .doc.
-
Type the placeholders. Write
{{ month }}where the month goes,{{ salesamount }}where the total goes, and so on. Names are case-sensitive and may contain letters, digits and underscores, but no spaces. -
Insert a dummy picture where the chart goes. Insert any picture with Insert > Pictures from a file with a fixed name, for example Placeholder_1.png. Python later swaps that picture by its original file name.
-
List the names in Excel. In the example workbook, the PANEL sheet holds every placeholder name in column A and its value in column B, starting in row 2. That two-column layout turns into the dictionary docxtpl needs with one line of code.
Tag cheat sheet
docxtpl understands Jinja2 tags plus a few Word-specific ones. These are the tags I use most, all tested with docxtpl 0.20.2. The p and tr variants remove the whole paragraph or table row that holds the tag, so no empty lines are left behind.
| Goal | Type this in Word | Notes |
|---|---|---|
| Insert a value | {{ customer }} |
A missing key renders as nothing, without an error |
| Format a number | {{ '{:,.2f}'.format(total) }} |
1234.5 becomes 1,234.50 |
| Fallback for an empty value | {{ date|default('n/a') }} |
Shows n/a when the key is missing |
| Show a paragraph only sometimes | {%p if overdue %}, then the paragraph, then {%p endif %} |
Each tag in its own paragraph |
| One table row per item | {%tr for item in items %} in a row above, {{ item.name }} in the cells of the middle row, {%tr endfor %} in a row below |
The tag rows disappear; the middle row repeats |
| Picture from code | {{ logo }} |
Pass InlineImage(doc, "logo.png", Cm(5)) as the value |
| Swap an existing picture | A dummy picture inserted from Placeholder_1.png | doc.replace_pic("Placeholder_1.png", "chart.png") keeps its size and position |
With those tags in a template, this context fills an invoice with a conditional warning and one table row per item:
from docxtpl import DocxTemplate # pip install docxtpl
doc = DocxTemplate("invoice_template.docx")
context = {
"customer": "Ana",
"total": 1234.5,
"overdue": True,
"items": [{"name": "Chairs", "qty": 3}, {"name": "Desk", "qty": 1}],
}
doc.render(context, autoescape=True)
doc.save("invoice_Ana.docx")
The output reads “Dear Ana,” and “Total: 1,234.50 USD”, shows the overdue paragraph, and has two item rows: Chairs 3 and Desk 1. With "overdue": False the paragraph is gone. autoescape=True matters as soon as a value can contain & or <; the troubleshooting section shows why.
A first render
The smallest useful script loads the template, builds a dictionary with one key per placeholder, renders and saves. This one from the Create_Your_Own_Template folder of the repository also inserts two pictures with InlineImage, 5 cm wide each:
from pathlib import Path # core library
from docx.shared import Cm, Emu, Inches, Mm # pip install python-docx
from docxtpl import DocxTemplate, InlineImage # pip install docxtpl
# Path settings
current_dir = Path(__file__).parent
template_path = current_dir / "Template.docx"
output_path = current_dir / "Template_Rendered.docx"
img_placeholder1_path = current_dir / "Placeholders" / "Placeholder_1.png"
img_placeholder2_path = current_dir / "Placeholders" / "Placeholder_2.png"
doc = DocxTemplate(template_path)
placeholder_1 = InlineImage(doc, str(img_placeholder1_path), Cm(5))
placeholder_2 = InlineImage(doc, str(img_placeholder2_path), Cm(5))
context = {
"name": "Sven",
"placeholder_1": placeholder_1,
"placeholder_2": placeholder_2,
}
doc.render(context)
doc.save(output_path)
Run it and Template_Rendered.docx appears next to the script with “Hello, my name is Sven.” and both pictures. To see which placeholders a template expects, print doc.get_undeclared_template_variables() before rendering.
Fill the template from Excel
This version reads the values straight from the workbook file with pandas, so Excel does not even need to be open, and it runs on Windows, Mac and Linux. It builds the context from the PANEL sheet, groups the Sales sheet by sub-category, draws a bar chart, swaps it into the template and saves the report.
from pathlib import Path
import matplotlib.pyplot as plt # pip install matplotlib
import pandas as pd # pip install pandas openpyxl
from docxtpl import DocxTemplate # pip install docxtpl
BASE_DIR = Path(__file__).parent
WORKBOOK = BASE_DIR / "word_automation.xlsm"
TEMPLATE = BASE_DIR / "Sales_Report_TEMPLATE.docx"
# PANEL sheet: placeholder names in column A, values in column B
panel = pd.read_excel(WORKBOOK, sheet_name="PANEL", usecols="A:B").dropna()
context = {
name: int(value) if isinstance(value, float) else value
for name, value in zip(panel["Placeholder"], panel["Value"])
}
# Sales sheet: one row per order line
sales = pd.read_excel(WORKBOOK, sheet_name="Sales")
by_subcategory = sales.groupby("Sub-Category")[["Sales"]].sum().sort_values(by="Sales")
# Bar chart, saved as PNG
chart_path = BASE_DIR / "sales_by_subcategory.png"
ax = by_subcategory.plot(kind="barh", legend=False)
ax.figure.savefig(chart_path, dpi=300, bbox_inches="tight")
plt.close(ax.figure)
# Fill the template and save the report
doc = DocxTemplate(TEMPLATE)
doc.replace_pic("Placeholder_1.png", str(chart_path))
doc.render(context, autoescape=True)
output_path = BASE_DIR / f"Sales_Report_{context['month']}.docx"
doc.save(output_path)
print(f"Saved {output_path.name}")
Put the script next to word_automation.xlsm and Sales_Report_TEMPLATE.docx from the repository and run it. With the sample data it saves Sales_Report_April.docx, with “In the month of April we have generated 83829 USD.”, the top three products (Chairs, Storage, Phones) in the table and the new chart in place of the dummy picture. int(value) cuts off the decimals the same way the xlwings version below does; drop it if you format numbers in the template instead.
For one document per row of a list, such as certificates or contracts, loop over the rows and render a fresh DocxTemplate each time. Generate Word documents in bulk from an Excel list shows that version.
Run it from a button in Excel
In the video, a button in word_automation.xlsm runs the script through xlwings, so a colleague only clicks in Excel. The script reads the open workbook with xw.Book.caller(), creates the chart, renders the template, saves a PDF copy through Word and shows a message box. Windows only, because the PDF step drives Word.
This is the repository script with two fixes. The original grouped the whole Sales table, which current pandas versions refuse with “TypeError: datetime64 type does not support operation ‘sum'” because of the Order Date column; it now sums only the Sales column. And convert_to_pdf now closes Word with word.Quit(), so no hidden Word process stays behind after each run.
from pathlib import Path # core library
import matplotlib.pyplot as plt # pip install matplotlib
import pandas as pd # pip install pandas
import win32com.client as win32 # pip install pywin32
import xlwings as xw # pip install xlwings
from docxtpl import DocxTemplate # pip install docxtpl
# -- Documentation:
# python-docx-template: https://docxtpl.readthedocs.io/en/latest/
def create_barchart(df, barchart_output):
"""Group DataFrame by sub-category, plot barchart, save plot as PNG"""
top_products = df.groupby("Sub-Category")[["Sales"]].sum()
top_products = top_products.sort_values(by="Sales")
plt.rcParams["figure.dpi"] = 300
plot = top_products.plot(kind="barh")
fig = plot.get_figure()
fig.savefig(barchart_output, bbox_inches="tight")
return None
def convert_to_pdf(doc):
"""Convert given word document to pdf"""
word = win32.DispatchEx("Word.Application")
new_name = doc.replace(".docx", ".pdf")
worddoc = word.Documents.Open(doc)
worddoc.SaveAs(new_name, FileFormat=17)
worddoc.Close()
word.Quit()
return None
def main():
# Path settings
current_dir = Path(__file__).parent
template_path = current_dir / "Sales_Report_TEMPLATE.docx"
# Conection to Excel
wb = xw.Book.caller()
sht_panel = wb.sheets["PANEL"]
sht_sales = wb.sheets["Sales"]
context = sht_panel.range("A2").options(dict, expand="table", numbers=int).value
df = sht_sales.range("A1").options(pd.DataFrame, index=False, expand="table").value
# Initialize template
doc = DocxTemplate(str(template_path))
# -- Create Barchart & Replace Placeholder
barchart_name = "sales_by_subcategory"
barchart_output = current_dir / f"{barchart_name}.png"
create_barchart(df, barchart_output)
doc.replace_pic("Placeholder_1.png", barchart_output)
# -- Render & Save Word Document
output_name = current_dir / f'Sales_Report_{context["month"]}.docx'
doc.render(context)
doc.save(output_name)
# -- Convert to PDF [OPTIONAL]
convert_to_pdf(str(output_name))
# -- Show Message Box [OPTIONAL]
show_msgbox = wb.macro("Module1.ShowMsgBox")
show_msgbox("DONE!")
if __name__ == "__main__":
xw.Book("word_automation.xlsm").set_mock_caller()
main()
The key line is sht_panel.range("A2").options(dict, expand="table", numbers=int).value: it reads the two PANEL columns into a dictionary and turns every number into a whole number. The block under if __name__ == "__main__": lets you run the same file from your editor while the workbook is open, which is the easiest way to debug it. If Excel shows “To enable RunPython, please run ‘xlwings runpython install’ in a terminal once and try again.”, do exactly that and click the button again.
Save the report as PDF
docxtpl only writes .docx files, so a PDF needs a program that can lay out Word documents. On Windows with Word installed, convert_to_pdf above does it through Word itself (FileFormat 17 is PDF), which gives the most faithful result.
Without Word, or on a Mac or Linux machine, LibreOffice converts from the command line. I converted the sample report this way:
soffice --headless --convert-to pdf Sales_Report_April.docx
On Windows, soffice.exe lives in C:\Program Files\LibreOffice\program unless that folder is on your PATH. Fonts that are not installed on the converting machine are replaced, so check the first PDF by eye.
docxtpl or python-docx
Use docxtpl when the layout already exists and only the values change. Use python-docx when the script has to build the document’s structure itself. docxtpl runs on top of python-docx, so you can mix both in one script.
| docxtpl | python-docx | |
|---|---|---|
| Layout comes from | A Word template you design | Your Python code |
| Conditions and loops | Yes, in the template | Yes, in Python |
| Best for | Reports, letters, contracts from data | Documents generated from scratch, editing existing files |
| Output | .docx (PDF through Word or LibreOffice) | .docx |
If nobody on the team should maintain a script, my ExcelToWord tool does the template part without code: the same kind of Word template with placeholders for text, pictures, tables and charts, filled from your sheet with one document per row, as Word, PDF or both.
For replacing words across many existing documents rather than filling a template, see replace text in multiple Word documents with Python. If your documents are invoices with a varying number of lines, my post on bulk PDF invoices from Excel draws them with ReportLab instead of a Word template.
Troubleshooting
Most docxtpl problems show up as an empty spot in the output or one of a few exceptions. I reproduced each of these with docxtpl 0.20.2.
- A placeholder renders as nothing. Cause: The context has no key with exactly that name (names are case-sensitive). Fix: Compare with
doc.get_undeclared_template_variables(), or render withjinja_env=jinja2.Environment(undefined=jinja2.StrictUndefined)to get “UndefinedError: ‘city’ is undefined”. - An & or text in < > disappears (“Smith & Sons” becomes “Smith Sons”). Cause: The value is pasted into the document’s XML unescaped. Fix: Render with
doc.render(context, autoescape=True). - TemplateSyntaxError: unexpected ‘}’. Cause: A tag has a missing or extra brace. Fix: Retype the tag; every
{{needs a}}and every{%a%}. - ValueError: Picture Placeholder_1.png not found in the docx template. Cause:
replace_piclooks for the file name the picture had when it was inserted. Fix: Insert the dummy picture again from a file with exactly that name. - TypeError: datetime64 type does not support operation ‘sum’. Cause: pandas 2 and newer no longer skip date columns in a groupby sum. Fix: Sum only the column you need:
df.groupby("Sub-Category")[["Sales"]].sum(). - ModuleNotFoundError: No module named ‘docxtpl’. Cause: The package went into a different Python. Fix: Install with
python -m pip install docxtplusing the same python that runs the script.
A tag that Word split into several formatting runs (for example after you made part of it bold) still rendered in my tests. If a tag stays visible in the output anyway, delete it and type it again in one go with one formatting.
FAQ
Can Python move data from Word to Excel?
Yes. python-docx reads Word tables and pandas writes them to Excel. This reads the first table of a document into a sheet, header row included:
import docx # pip install python-docx
import pandas as pd # pip install pandas openpyxl
doc = docx.Document("Sales_Report_April.docx")
table = doc.tables[0]
rows = [[cell.text for cell in row.cells] for row in table.rows]
df = pd.DataFrame(rows[1:], columns=rows[0])
df.to_excel("word_table.xlsx", index=False)
Every value arrives as text, so convert number columns with pd.to_numeric if you want to calculate with them.
Does docxtpl need Microsoft Word?
No. docxtpl reads and writes the .docx file directly, so it runs on any system with Python. You only need Word for the PDF export through pywin32 and to design the template.
Where is the official docxtpl documentation?
On docxtpl.readthedocs.io. It lists every tag, RichText for formatted values, subdocuments and the full API.
Resources
If you would rather not maintain the script, this does the same job with no code: a Word template plus your sheet, one document per row.
