Mail Merge (2)
Python: Create and Execute Conditional Mail Merges in Word Documents
2024-08-09 00:54:29 Written by support iceblueConditional mail merge in Word documents is a powerful method for personalized communication at scale. Unlike other mail merges that apply the same template to all recipients, conditional mail merge allows users to customize content based on specific criteria or conditions, ensuring that each recipient receives information that is directly relevant to them. By leveraging Python, users can automate the creation and execution of conditional mail merges.
This article will show how to create and execute conditional mail merges in Word documents through Python code using Spire.Doc for Python.
- Create Conditional Mail Merge in a Word Document with Python
- Execute Conditional Mail Merge in a Word Document with Python
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 Conditional Mail Merge in a Word Document with Python
A conditional mail merge uses an If field containing a mail merge field, which alters the merge results based on the data. To add a conditional mail merge to a Word document, insert an If field, then include a mail merge field within the If field’s code, and finish by adding the field end mark to complete the setup. The condition is controlled by the code within the If field.
The detailed steps for adding a conditional mail merge to a Word document are as follows:
- Create an instance of the Document class to generate a Word document.
- Add a section to the document and configure the page setup.
- Create paragraph styles, add paragraphs, and set their formats.
- Create an IfField object, set its starting code through the IfField.Code property, and insert it into a paragraph using the Paragraph.Items.Add() method.
- Append a mail merge field to the paragraph using the Paragraph.AppendField() method.
- Append the remaining code to the paragraph using the Paragraph.AppendText() method.
- Append a field end mark to end the If field using the Paragraph.AppendFieldMark() method.
- Set the end mark as the end mark of the If field through the IfField.End property.
- Save the document using the Document.SaveToFile() method.
- Python
from spire.doc import * # Create an instance of Document doc = Document() # Add a section to the document section = doc.AddSection() # Set the page size and margins section.PageSetup.PageSize = PageSize.A4() section.PageSetup.Margins.All = 50 # Create a paragraph style style = ParagraphStyle(doc) style.Name = "Style1" style.CharacterFormat.FontName = "Arial" style.CharacterFormat.FontSize = 14 style.ParagraphFormat.BeforeSpacing = 5 style.ParagraphFormat.AfterSpacing = 10 doc.Styles.Add(style) # Add paragraphs and set the style paragraph = section.AddParagraph() paragraph.AppendText("Dear ") paragraph.AppendField("FirstName", FieldType.FieldMergeField) paragraph.AppendText(" ") paragraph.AppendField("LastName", FieldType.FieldMergeField) paragraph.AppendText(",") paragraph.ApplyStyle(style.Name) paragraph = section.AddParagraph() paragraph.AppendText("\r\nThank you for being a valued customer. We appreciate your business and support.") paragraph.ApplyStyle(style.Name) # Add an If field to a paragraph paragraph = section.AddParagraph() ifField = IfField(doc) ifField.Type = FieldType.FieldIf ifField.Code = "IF " paragraph.Items.Add(ifField) # Add a mail merge field in the code of the If field paragraph.AppendField("CustomerType", FieldType.FieldMergeField) paragraph.AppendText(" = ") paragraph.AppendText("\"VIP\"") paragraph.AppendText(" \"As a VIP customer, we have a special offer just for you! Enjoy a 20% discount on your next " "purchase.\"") paragraph.AppendText("\"We appreciate you choosing us! Please keep an eye out for our future special offers and " "discounts.\"") # Add a field end mark at the end to end the If field endIf = paragraph.AppendFieldMark(FieldMarkType.FieldEnd) ifField.End = endIf paragraph.ApplyStyle(style.Name) # Add paragraphs and set the style paragraph = section.AddParagraph() paragraph.AppendText("Your total spending with us is ") paragraph.AppendField("TotalSpent", FieldType.FieldMergeField) paragraph.ApplyStyle(style.Name) paragraph = section.AddParagraph() paragraph.AppendText("\r\nBest regards,\r\nTech Inc.") paragraph.ApplyStyle(style.Name) # Save the document doc.SaveToFile("output/ConditionalMailMerge.docx", FileFormat.Docx) doc.Close()
Execute Conditional Mail Merge in a Word Document with Python
The Document.MailMerge.Execute(fieldNames: list[str], fieldValues: list[str]) method provided by Spire.Doc for Python allows for mail merge operations within Word documents. After the merge, you can update the results of conditional mail merges by setting the Document.IsUpdateFields property to True. The detailed steps are as follows:
- Read the data in the table used for the merge as a two-dimensional list.
- Iterate through the data rows, skipping the header:
- Create an instance of the Document class and load the Word document to be merged.
- Get the names of the mail merge fields as a list using the Document.MailMerge.GetMergeFieldNames() method.
- Execute the mail merge with the data using the Document.MailMerge.Execute() method.
- Update the If field by setting the Document.IsUpdateFields property to True.
- Save the document using the Document.SaveToFile() method.
- Python
from spire.doc import * import csv # Read the data from a CSV file data = [] with open("Customers.csv", "r") as csvfile: read = csv.reader(csvfile) for row in read: data.append(row) # Iterate through the data rows by skipping the header for i in range(1, len(data)): # Create an instance of Document and load a Word document doc = Document("output/ConditionalMailMerge.docx") # Get the field names from the document fieldNames = doc.MailMerge.GetMergeFieldNames() # Execute the mail merge doc.MailMerge.Execute(fieldNames, data[i]) # Update the If field doc.IsUpdateFields = True # Save the document doc.SaveToFile(f"output/Customers/{data[i][0]} {data[i][1]}.docx", FileFormat.Docx2019) doc.Close()
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.
Python: Create and Execute Mail Merge in Word Documents
2024-04-23 00:57:05 Written by support iceblueMail 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()
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()
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.