How to display mail merge result using format switch in the Word document
Syncfusion Essential DocIO is a .NET Word library used to create, read, and edit Word documents programmatically without Microsoft Word or interop dependencies. Using this library, you can display mail merge results by using a format switch in the Word document.
Display mail merge results using a format switch in the Word document using C#:
- Create a new C# console application project.
- Install the Syncfusion.DocIO.WinForms NuGet package as a reference to your .NET Framework applications from NuGet.org.
- Include the following namespace in the Program.cs file.
C#
using Syncfusion.DocIO; using Syncfusion.DocIO.DLS;
VB
Imports Syncfusion.DocIO Imports Syncfusion.DocIO.DLS
- Use the following code example to display mail merge results using a format switch in the Word document.
C#
//Open the template document. using (WordDocument wordDocument = new WordDocument("Data\\Template.docx", FormatType.Docx)) { //Process the body contents for each section in the Word document. foreach (WSection section in wordDocument.Sections) { //Access the body of the section where all the contents of the document are apart. WTextBody sectionBody = section.Body; IterateTextBody(sectionBody); } //Perform the mail merge. Console.WriteLine("Performing MailMerge"); string[] fieldNames = new string[] { "Name", "DOB", "Salary Amount" }; string[] fieldValues = new string[] { "Daniel Raj", "06/02/1997", "45678" }; wordDocument.MailMerge.ClearFields = true; wordDocument.MailMerge.Execute(fieldNames, fieldValues); //Save the Word document. wordDocument.Save("Template.docx"); }
VB
'Open the template document. Using wordDocument As WordDocument = New WordDocument("Data\Template.docx", FormatType.Docx) 'Process the body contents for each section in the Word document. For Each section As WSection In wordDocument.Sections 'Access the body of section where all the contents of the document are apart. Dim sectionBody As WTextBody = section.Body IterateTextBody(sectionBody) Next 'Perform the mail merge. Console.WriteLine("Performing MailMerge") Dim fieldNames() As String = New String() {"Name", "DOB", "Salary Amount"} Dim fieldValues() As String = New String() {"Daniel Raj", "06/02/1997", "45678"} wordDocument.MailMerge.ClearFields = True wordDocument.MailMerge.Execute(fieldNames, fieldValues) 'Save the Word document. wordDocument.Save("Template.docx") End Using
- Helper Methods.
C#
private static void IterateTextBody(WTextBody textBody) { //Iterate through each of the child items of WTextBody. for (int i = 0; i < textBody.ChildEntities.Count; i++) { //IEntity is the basic unit in the DocIO DOM. //Access the body items (should be either paragraph, table or block content control) as IEntity IEntity bodyItemEntity = textBody.ChildEntities[i]; //A Text body has 3 types of elements - Paragraph, Table and Block Content Control. //Decide the element type by using EntityType. switch (bodyItemEntity.EntityType) { case EntityType.Paragraph: WParagraph paragraph = bodyItemEntity as WParagraph; //Process the paragraph content. //Iterate through the paragraph's DOM. IterateParagraph(paragraph.Items); break; case EntityType.Table: // A Table is a collection of rows and cells. //Iterate through table's DOM. IterateTable(bodyItemEntity as WTable); break; case EntityType.BlockContentControl: BlockContentControl blockContentControl = bodyItemEntity as BlockContentControl; //Iterate through the body items of Block Content Control. IterateTextBody(blockContentControl.TextBody); break; } } } private static void IterateTable(WTable table) { //Iterate the row collection in a table. foreach (WTableRow row in table.Rows) { //Iterate the cell collection in a table row. foreach (WTableCell cell in row.Cells) { //Table cell is derived from (also a) TextBody //Reusing the code meant for iterating TextBody IterateTextBody(cell); } } } private static void IterateParagraph(ParagraphItemCollection paraItems) { for (int i = 0; i < paraItems.Count; i++) { Entity item = paraItems[i]; if (item is WField) { WField field = item as WField; //Text format switch (\*). if ((item as WField).FieldType == FieldType.FieldMergeField && (item as WMergeField).FieldName == "Name") { field.FieldCode = "MERGEFIELD Name \\* Upper"; } //Date-time format switch (\@). else if ((item as WField).FieldType == FieldType.FieldMergeField && (item as WMergeField).FieldName == "DOB") { field.FieldCode = "MERGEFIELD DOB \\@" + "\"MMMM d, yyyy\""; } //Numeric format switch (\#). else if ((item as WField).FieldType == FieldType.FieldMergeField && (item as WMergeField).FieldName == "Salary Amount") { field.FieldCode = "MERGEFIELD Salary Amount \\# $#,##0.00"; } } } }
VB
Private Shared Sub IterateTextBody(ByVal textBody As WTextBody) 'Iterate through each of the child items of WTextBody Dim i As Integer = 0 Do While (i < textBody.ChildEntities.Count) 'IEntity is the basic unit in the DocIO DOM. 'Access the body items (should be either paragraph, table or block content control) as IEntity. Dim bodyItemEntity As IEntity = textBody.ChildEntities(i) 'A Text body has 3 types of elements - Paragraph, Table and Block Content Control 'Decide the element type by using EntityType Select Case (bodyItemEntity.EntityType). Case EntityType.Paragraph Dim paragraph As WParagraph = CType(bodyItemEntity, WParagraph) 'Process the paragraph content. 'Iterate through the paragraph's DOM. IterateParagraph(paragraph.Items) Case EntityType.Table ' A Table is a collection of rows and cells. 'Iterate through table's DOM. IterateTable(CType(bodyItemEntity, WTable)) Case EntityType.BlockContentControl Dim blockContentControl As BlockContentControl = CType(bodyItemEntity, BlockContentControl) 'Iterate to the body items of Block Content Control. IterateTextBody(blockContentControl.TextBody) End Select i = (i + 1) Loop End Sub Private Shared Sub IterateTable(ByVal table As WTable) 'Iterate the row collection in a table. For Each row As WTableRow In table.Rows 'Iterate the cell collection in a table row. For Each cell As WTableCell In row.Cells 'Table cell is derived from (also a) TextBody. 'Reusing the code meant for iterating TextBody. IterateTextBody(cell) Next Next End Sub Private Shared Sub IterateParagraph(ByVal paraItems As ParagraphItemCollection) Dim i As Integer = 0 Do While (i < paraItems.Count) Dim item As Entity = paraItems(i) If (TypeOf item Is WField) Then Dim field As WField = CType(item, WField) 'Text format switch (\*). If ((CType(item, WField).FieldType = FieldType.FieldMergeField) _ AndAlso (CType(item, WMergeField).FieldName = "Name")) Then field.FieldCode = "MERGEFIELD Name \* Upper" 'Date-time format switch (\@). ElseIf ((CType(item, WField).FieldType = FieldType.FieldMergeField) _ AndAlso (CType(item, WMergeField).FieldName = "DOB")) Then field.FieldCode = ("MERGEFIELD DOB \@" + """MMMM d, yyyy""""") 'Numeric format switch (\#). ElseIf ((CType(item, WField).FieldType = FieldType.FieldMergeField) _ AndAlso (CType(item, WMergeField).FieldName = "Salary Amount")) Then field.FieldCode = "MERGEFIELD Salary Amount \# $#,##0.00" End If End If i = (i + 1) Loop End Sub
A complete working example to display mail merge results using format switch in the Word document using C# can be downloaded from Sample.
Take a moment to peruse the documentation, where you can find the basic Word document processing options along with features like mail merge, merge and split documents, find and replace text in the Word document, protect the Word documents, and most importantly, PDF and Image conversions with code examples.
Explore more about the rich set of Syncfusion Word Framework features.
Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering a Syncfusion license key in your application to use the components without trail message.