Generate MS Word Documents from Mail Merge Template in Python

MS Word mail merge is a popular feature that allows you to create letters, invoices, envelopes, reports, etc. Using mail merge, you can create a template and populate it with the data. As a result, a document is generated for each entry in the data source. To automate this feature, this article covers how to perform MS Word mail merge using Python. You will learn how to create a mail merge template from scratch and populate it programmatically.

Python Library to Automate MS Word Mail Merge

To automate MS Word mail merge, we will use Aspose.Words for Python. It is a powerful library that lets you create and manipulate Word documents. Moreover, it allows you to create the mail merge templates and populate them seamlessly. Aspose.Words for Python can be installed from PyPI using the following pip command.

pip install aspose-words 

Create a Mail Merge Template in Python

A mail merge template contains merge fields that are populated with the values in the data source. The template could be of DOT, DOTX, DOC, or DOCX format. In order to create a mail merge template, you can use MS Word. However, to automate this procedure in Python, you can follow the below steps.

  • Create an object of DocumentBuilder class.
  • Insert text using DocumentBuilder.insert_text_input() method.
  • Insert the merge field using DocumentBuilder.insert_field() method.
  • Repeat inserting text and merge fields as required.
  • Save the template as a file using DocumentBuilder.document.save() method.

The following code sample shows how to create a DOCX mail merge template using Python.

import aspose.words as aw
# Create a document builder
builder = aw.DocumentBuilder()
# Insert a text input field the unique name of this field is "Hello", the other parameters define
# what type of FormField it is, the format of the text, the field result and the maximum text length (0 = no limit)
builder.insert_text_input("TextInput", aw.fields.TextFormFieldType.REGULAR, "", "Hello ", 0)
builder.insert_field("MERGEFIELD CustomerFirstName \\* MERGEFORMAT")
builder.insert_text_input("TextInput1", aw.fields.TextFormFieldType.REGULAR, "", " ", 0)
builder.insert_field("MERGEFIELD CustomerLastName \\* MERGEFORMAT")
builder.insert_text_input("TextInput1", aw.fields.TextFormFieldType.REGULAR, "", " , ", 0)
# Insert a paragraph break into the document
builder.insert_paragraph()
# Insert mail body
builder.insert_text_input("TextInput", aw.fields.TextFormFieldType.REGULAR, "", "Thanks for purchasing our ", 0)
builder.insert_field("MERGEFIELD ProductName \\* MERGEFORMAT")
builder.insert_text_input("TextInput", aw.fields.TextFormFieldType.REGULAR, "", ", please download your Invoice at ", 0)
builder.insert_field("MERGEFIELD InvoiceURL \\* MERGEFORMAT")
builder.insert_text_input("TextInput", aw.fields.TextFormFieldType.REGULAR, "", ". If you have any questions please call ", 0)
builder.insert_field("MERGEFIELD Supportphone \\* MERGEFORMAT")
builder.insert_text_input("TextInput", aw.fields.TextFormFieldType.REGULAR, "", ", or email us at ", 0)
builder.insert_field("MERGEFIELD SupportEmail \\* MERGEFORMAT")
builder.insert_text_input("TextInput", aw.fields.TextFormFieldType.REGULAR, "", ".", 0)
builder.insert_paragraph()
# Insert mail ending
builder.insert_text_input("TextInput", aw.fields.TextFormFieldType.REGULAR, "", "Best regards,", 0)
builder.insert_break(aw.BreakType.LINE_BREAK)
builder.insert_field("MERGEFIELD EmployeeFullname \\* MERGEFORMAT")
builder.insert_text_input("TextInput1", aw.fields.TextFormFieldType.REGULAR, ",", " ", 0)
builder.insert_field("MERGEFIELD EmployeeDepartment \\* MERGEFORMAT")
# Save the template as a DOCX file
builder.document.save("mail_merge_template.docx")

The following is the screenshot of the template we have just created using the code sample above.

creating a mail merge template in python

Generate Word Document using Mail Merge Template in Python

Now when you have created the mail merge template, it’s time to populate its fields with values. The following are the steps to generate a Word document from a mail merge template in Python.

  • Load the mail merge template using Document class.
  • Call Document.mail_merge.execute() method and pass data in the form of an array.
  • Save the generated document using Document.save() method.

The following code sample shows how to generate a Word document from mail merge template.

import aspose.words as aw
# Load the mail merge template
doc = aw.Document("mail_merge_template.docx")
# Fill the fields in the document with data
doc.mail_merge.execute(["CustomerFirstName", "CustomerLastName", "ProductName", "InvoiceURL", "SupportPhone", "SupportEmail", "EmployeeFullname", "EmployeeDepartment"],
["John", "Doe", "Aspose.Words", "aspose.com", "111-222-333", "support@aspose.com", "Jimmy", "Sales"]
)
# Save the document
doc.save("mail_merge_populated.docx")

The following screenshot shows the Word document that we have generated from the mail merge template.

generate word document from mail merge template in python

Get a Free License

You can use Aspose.Words for Python without evaluation limitations by getting a free temporary license.

Conclusion

MS Word mail merge is a useful feature to generate Word documents from predefined templates. To automate mail merge, this article covered how to create mail merge templates and populate them with data in Python. You can also explore other features of Aspose.Words for Python using the documentation. In case you would have any questions, feel free to post them to our forum.

See Also