Python: Create and Execute Mail Merge in Word Documents

Mail merge is a powerful tool that allows users to efficiently create personalized documents for a large number of recipients. By using mail merge, users can streamline the document-creating process by automatically merging a template document with a data source, resulting in personalized and professional-looking documents that are tailored to each recipient, which is especially useful for tasks like sending out personalized emails, generating invoices, or creating customized marketing materials. This article demonstrates how to create and execute mail merge in Word documents with Spire.Doc for Python through Python code.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to: How to Install Spire.Doc for Python on Windows

Create Mail Merge in Word Documents with Python

Mail merging in Word documents involves the utilization of mail merge fields. Spire.Doc for Python offers the Paragraph.AppendField(str: fieldName, FieldType.FieldMergeField) method, which allows users to efficiently create mail merge fields within a designated paragraph of a document. This feature enables users to easily generate a set of documents tailored to specific recipients by swiftly inputting personalized information at a later stage.

The detailed steps for creating mail merge fields in Word documents are as follows:

  • Create an object of Document class and load a Word document using Document.LoadFromFile() method.
  • Get a section using Document.Sections.get_Item() method.
  • Get the paragraphs to insert mail merge fields using Section.Paragraphs.get_Item() method.
  • Append mail merge fields to the paragraphs using Paragraph.AppendField() method.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an object of Document class
doc = Document()

# Load a Word document
doc.LoadFromFile("Sample.docx")

# Get a section
section = doc.Sections.get_Item(1)

# Get the paragraphs to append the mail merge fields
para1 = section.Paragraphs.get_Item(0)
para2 = section.Paragraphs.get_Item(1)
para3 = section.Paragraphs.get_Item(2)
para4 = section.Paragraphs.get_Item(3)

# Append the mail merge fields and specify the field names
para1.AppendField("Name", FieldType.FieldMergeField)
para2.AppendField("Age", FieldType.FieldMergeField)
para3.AppendField("Phone Number", FieldType.FieldMergeField)
para4.AppendField("Membership Type", FieldType.FieldMergeField)

# Save the document
doc.SaveToFile("output/MailMergeFields.docx", FileFormat.Docx)
doc.Close()

Python: Create and Execute Mail Merge in Word Documents

Perform Mail Merge in Word Documents with Python

Once the mail merge has been created, the MailMerge.Execute(List: fieldNames, List: dataSource) method can be employed to execute the mail merge within the document. This enables the swift generation of multiple Word documents, each containing unique content as per the specified data source.

The detailed steps for performing mail merge and generate personalized documents are as follows:

  • Specify the data source
  • Loop through the data source:
    • Create an object of Document class and load a Word document using Document.LoadFromFile() method.
    • Get the mail merge field names as a list using Document.MailMerge.GetMergeFieldNames() method.
    • Execute mail merge with specified data using Document.MailMerge.Execute() method.
    • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import Document

# Specify the data source
dataSource = member_data = [
    ["Alice Johnson", "35", "+1-555-123-4567", "Premium"],
    ["Bob Williams", "42", "+1-555-765-4321", "Standard"],
    ["Charlie Brown", "28", "+44-1234-567890", "Basic"],
]

# Loop through the data source
for i in range(len(dataSource)):
    # Create an instance of Document
    doc = Document()
    # Load a Word document with mail merge fields
    doc.LoadFromFile("output/MailMergeFields.docx")
    # Get the merge field names
    fieldNames = doc.MailMerge.GetMergeFieldNames()
    # Execute mail merge
    doc.MailMerge.Execute(fieldNames, dataSource[i])
    # Save the document
    doc.SaveToFile(f"output/Members/Member-{dataSource[i][0]}.docx")
doc.Close()

Python: Create and Execute Mail Merge in Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.