Using Python to Automatically Populate Word Documents

Posted by

In this tutorial, we will explore how to automatically fill Word files with Python using the python-docx library. This can be useful for generating personalized documents, filling in form letters, or automating the creation of reports.

Before we begin, make sure you have Python and the python-docx library installed on your system. You can install the library by running the following command:

pip install python-docx

Once you have the library installed, let’s get started by creating a new Python script. We will start by importing the necessary modules:

from docx import Document

Next, we will create a function that will open a Word file, fill in the placeholders with the provided values, and save the filled file:

def fill_word_template(template_file, output_file, values):
    doc = Document(template_file)

    for p in doc.paragraphs:
        for key, value in values.items():
            if key in p.text:
                p.text = p.text.replace(key, value)

    doc.save(output_file)

In the code above, the fill_word_template function takes three arguments: the path to the Word template file, the path to the output file, and a dictionary of values to fill in. The function opens the template file, searches for placeholders in the text, replaces them with the provided values, and saves the filled document to the output file.

Now let’s demonstrate how to use this function with a simple example. Create a new Word document (template.docx) with the following content:

Dear [name],

We are pleased to inform you that you have been selected for the position of [position] at our company.

Sincerely,
[company_name]

Next, create a new Python script and add the following code:

template_file = "template.docx"
output_file = "filled_document.docx"
values = {
    "[name]": "John Doe",
    "[position]": "Software Engineer",
    "[company_name]": "ABC Company"
}

fill_word_template(template_file, output_file, values)

In this example, we provide a dictionary of values to fill in the placeholders in the Word document. When we run the script, a new filled_document.docx file will be created with the placeholders replaced by the provided values.

You can customize the Word template and the values to fill in based on your specific requirements. This method can be used to automate the generation of various types of documents, such as contracts, reports, or personalized letters.

I hope this tutorial was helpful in learning how to automatically fill Word files with Python. Feel free to explore more features of the python-docx library to further enhance your document automation capabilities.

0 0 votes
Article Rating
26 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@wesamkiwan9561
2 months ago

who knows how we can make a loops in the templates. for example i have a list of orders for each customer and in the template i want to loop through the list of orders and add each order to the file, and each customer has different list length so i want to make loop to make it more dynamic.
i mean i want the loop to be within the template not in the code.

@jackbauer322
2 months ago

What if I wanted to fill the file with an LLM generation ?

@mrbusiness8648
2 months ago

Hero

@aimattant
2 months ago

Finally made it work with a little help from ChatGPT. I need to work on this to make it into a working app. Cheers

@iaconst4.0
2 months ago

Ese codigo falla a veces, es muy inestable , no reemplaza muchas veces.

@paulinepanganiban7938
2 months ago

interesting! thanks for this. new subscriber here! can you create content on creating python script to display computer name, cpuinfo , including users and their associated groups as well as status of services being run in the linux machine? 🙂 Thanks!

@r00tey545
2 months ago

Sadly getting the error – in terminal:
raise PackageNotFoundError("Package not found at '%s'" % pkg_file)
docx.opc.exceptions.PackageNotFoundError: Package not found at 'template1.docx'

@Biokompott
2 months ago

thank you, but I think, word has something built-in for this.

@EdwardTilley
2 months ago

Great video!

@muhammedhijazi4080
2 months ago

Which OS is this?

@StYxXx
2 months ago

I did something like this without extra packaged once in javascript. Just reading the file. You have to make sure the placeholders aren't splitted (which can happen in doc files, there can be tags within a word – you can edit the template though), but besides that it's a pretty forward string replacement.
This solutions seems to be way more easier though 🙂

@philtoa334
2 months ago

Thx_.

@vasukansal1834
2 months ago

please explain every line in a more easy way for those people who are using such modules first time

@ExcelInstructor
2 months ago

Hello,
Im just trying to start with python,
I have question:
what is that environment your coding in?
Can you go thru code like in VBA when you can execute line by line with f8?

@jvsonyt
2 months ago

This is great

@serychristianrenaud
2 months ago

Thanks

@PANDURANG99
2 months ago

Comments on word file

@Sebwazhere
2 months ago

I broke python by deleting a folder, I reinstalled it and nothing I do works, the folder I deleted was something like mingw/mingw62/lib/python 3.10 and now none of my python installations work and I just get the error: No module named 'encodings' when I try to run python.

@mikaelmanuel0407
2 months ago

I created a similar module using docxtemplate, openpyxl in python, and a separate command line script using a python module – docx2pdf to do it in bulk. Data prep was really necessary

@vishnubalaji9500
2 months ago

can you make a video for controlling/automating power bi dashboards