Articles in this section

How to Modify Number or Date Formats in Word Mail Merge Fields at Runtime using C# .NET Core?

Syncfusion® Essential® DocIO is a .NET Word library used to create, read, edit, and convert Word documents programmatically without Microsoft Word or interop dependencies. Using this library, you can modify number or date formats in Word mail merge fields at runtime using C#.

Overview of the Custom Formatting Logic for Mail Merge Fields:

  • Open the template Word document.
  • Attach event handlers for merge fields.
  • Retrieve values from a data source and perform the mail merge and store each merge field’s index and owner paragraph in the separate collections (number fields and date fields).
  • After completing the mail merge process, iterate through the collections to get each paragraph and retrieve the merge field text based on the index.
  • For number fields, insert an IF field with a numeric picture switch ("#,##0.00”) to the format values.
  • For date field, insert an IF field with a date picture switch (@ “dd/MMM/yyyy”) to the format values.
  • Replace the original merge field text with the formatted result.
  • Clear the collections after processing.
  • Save and close the document.

Steps to modify number or date formats in Word mail merge fields at runtime:

  1. Create a new .NET Core console application project.
    Create console application in Visual Studio
  2. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your project from NuGet.org.
    Add DocIO NuGet package reference to the project
Note:

Starting with v16.2.0.x, if you reference Syncfusion® assemblies from a 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 a trial message.

  1. Include the following namespaces in the Program.cs file.
    C#
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO;
using System.Data;
  1. Use the following dictionary to store paragraphs along with their corresponding field values.
    C#
public static Dictionary<WParagraph, List<KeyValuePair<int, string>>> paratoModifyNumberFormat
   = new Dictionary<WParagraph, List<KeyValuePair<int, string>>>();
public static Dictionary<WParagraph, List<KeyValuePair<int, string>>> paratoModifyDateFormat
    = new Dictionary<WParagraph, List<KeyValuePair<int, string>>>();
  1. Use the following code example to perform mail merge.
    C#
 // Load the existing word document
 WordDocument document = new WordDocument(Path.GetFullPath(@"Data\Template.docx"));
 // Enable separate page for each invoice
 document.MailMerge.StartAtNewPage = true;
 document.MailMerge.MergeField += new MergeFieldEventHandler(MergeFieldEvent);
 // Perform mail merge
 document.MailMerge.ExecuteGroup(GetInvoiceData());
 // Update the merge field results with formatted values.
 UpdateMergeFieldResult(true);
 UpdateMergeFieldResult(false);
 // Save the Word document.
 document.Save(Path.GetFullPath(@"../../../Output/Output.docx"));
 // Close the document
 document.Close();
  1. Use the following code example to handle the MergeField event.
    C#
private static void MergeFieldEvent(object sender, MergeFieldEventArgs args)
{
    // Get the mergefield's Owner paragraph
    WParagraph mergeFieldOwnerParagraph = args.CurrentMergeField.OwnerParagraph;
    // Find the index of the current merge field within the paragraph.
    int index = mergeFieldOwnerParagraph.ChildEntities.IndexOf(args.CurrentMergeField);
    if (args.FieldName == "Amount")
    {
        // Check if this paragraph already has an entry in the dictionary.
        // If not, create a new list to store field index and field value.
        if (!paratoModifyNumberFormat.TryGetValue(mergeFieldOwnerParagraph, out var fields))
        {
            fields = new List<KeyValuePair<int, string>>();
            paratoModifyNumberFormat[mergeFieldOwnerParagraph] = fields;
        }
        // Add the current merge field's index and field name
        fields.Add(new KeyValuePair<int, string>(index, args.FieldValue.ToString()));
    }
    else if (args.FieldName == "InvoiceDate")
    {
        // Check if this paragraph already has an entry in the dictionary.
        // If not, create a new list to store field index and field value.
        if (!paratoModifyDateFormat.TryGetValue(mergeFieldOwnerParagraph, out var fields))
        {
            fields = new List<KeyValuePair<int, string>>();
            paratoModifyDateFormat[mergeFieldOwnerParagraph] = fields;
        }
        // Add the current merge field's index and field name
        fields.Add(new KeyValuePair<int, string>(index, args.FieldValue.ToString()));
    }
}
  1. Use the following code example to modify number or date formats for merge fields in a Word document at runtime.
    C#
 public static void UpdateMergeFieldResult(bool numberType)
 {
     Dictionary<WParagraph, List<KeyValuePair<int, string>>> mergeFieldResults;
     if (numberType)
         mergeFieldResults = paratoModifyNumberFormat;
     else
         mergeFieldResults = paratoModifyDateFormat;
     // Iterate the outer dictionary entries
     foreach (KeyValuePair<WParagraph, List<KeyValuePair<int, string>>> dictionaryItem in mergeFieldResults)
     {
         // Get the merge field result paragraph
         WParagraph mergeFieldParagraph = dictionaryItem.Key;
         // The list of (index, fieldValues) pairs for this paragraph.
         List<KeyValuePair<int, string>> fieldList = dictionaryItem.Value;               
         for (int i = 0; i <= fieldList.Count - 1; i++)
         {
             // Get the index and Field values ("Number" or "Date")
             int index = fieldList[i].Key;
             string fieldValue = fieldList[i].Value;
             // Get the existing merge field result text at the specified index.
             WTextRange mergeFieldText = (WTextRange)mergeFieldParagraph.ChildEntities[index];
             if (mergeFieldText != null)
             {
                 // Create the temporary document and insert the IF field.
                 WordDocument tempDocument = new WordDocument();
                 WSection section = (WSection)tempDocument.AddSection();
                 WParagraph ifFieldParagraph = (WParagraph)section.AddParagraph();
                 WIfField field = (WIfField)ifFieldParagraph.AppendField("IfField", Syncfusion.DocIO.FieldType.FieldIf);
                 // Check if the Number field value
                 if (numberType)
                 {
                     // Format number: 1,234.56 
                     field.FieldCode = $"IF 1 = 1 \"{fieldValue}\" \" \" \\# \"#,##0.00\"";
                 }
                 // Update the Date field value
                 else
                 {
                     // Format date: dd/MMM/yyyy
                     field.FieldCode = $"IF 1 = 1 \"{fieldValue}\" \" \" \\@ \"dd/MMM/yyyy\" ";
                 }
                 // Update the field and unlink
                 tempDocument.UpdateDocumentFields();
                 field.Unlink();
                 // Update the Merge field result
                 WTextRange modifiedText = (WTextRange)ifFieldParagraph.ChildEntities[0];
                 mergeFieldText.Text = modifiedText.Text;
                 // close the temp document
                 tempDocument.Close();
             }
         }
     }
     if (numberType)
         paratoModifyNumberFormat.Clear();
     else
         paratoModifyDateFormat.Clear();
 }
  1. Use the following code example to get the data to perform mail merge.
    C#
private static DataTable GetInvoiceData()
{
    DataTable table = new DataTable("Invoice");

    table.Columns.Add("InvoiceNumber");
    table.Columns.Add("InvoiceDate");
    table.Columns.Add("CustomerName");
    table.Columns.Add("ItemDescription");
    table.Columns.Add("Amount");           
    // First Invoice
    table.Rows.Add("INV001", "2024-05-01", "Andy Bernard", "Consulting Services", "3,000.578");
    // Second Invoice
    table.Rows.Add("INV002", "2024-05-05", "Stanley Hudson", "Software Development", "4,500.052");
    // Third Invoice
    table.Rows.Add("INV003", "2024-05-10", "Margaret Peacock", "UI Design Services", "2,000.600");

    return table;
}

You can download a complete working sample to modify number or date formats in Word mail merge fields at runtime from GitHub.

Final Output Image:

Output Word Document

Take a moment to peruse the documentation where you can find basic Word document processing options along with features like mail merge, merge, split, and compare Word documents, find and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples.

Conclusion

I hope you enjoyed learning about how to modify number or date formats in Word mail merge fields at runtime in a .NET Core Word document.

You can refer to our ASP.NET Core DocIO feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started with configuration specifications. You can also explore our ASP.NET Core DocIO example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Access denied
Access denied