Articles in this section
Category / Section

How to replace merge field with chart in Word document using mail merge?

5 mins read

Syncfusion Essential DocIO is a .NET Core Word library used to create, read, and edit Word documents programmatically without Microsoft Word or Interop dependencies. Using this library, you can replace merge field with chart using mail merge in Word document in C#.

Steps to replace merge field with chart using mail merge in Word document:

  1. Create a new C# .NET Core console application project. Create .NET Core console application in Visual Studio in ASP.NET Core Word
  2. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your .NET Core applications from NuGet.org.Add DocIO.Net.Core NuGet packages of ASP.NET Core Word
  3. Include the following namespace in the Program.cs file.

C#

using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.OfficeChart;
  1. Use the following code example to replace merge field with chart using mail merge in Word document.

C#

using (FileStream fileStream = new FileStream(Path.GetFullPath(@"../../../Template.docx"), FileMode.Open, FileAccess.ReadWrite))
{
    //Loads an existing Word document into DocIO instance.
    using (WordDocument document = new WordDocument(fileStream, FormatType.Automatic))
    {
        //Gets the employee details as “IEnumerable” collection
        List<Employees> employeeList = GetEmployeeData();
        //Creates an instance of MailMergeDataTable by specifying MailMerge group name and IEnumerable collection.
        MailMergeDataTable dataTable = new MailMergeDataTable("Employees", employeeList);
        //Uses the mail merge event handler to insert chart during mail merge.
        document.MailMerge.MergeField += new MergeFieldEventHandler(MergeField_EmployeeGraph);
        //Performs Mail merge.
        document.MailMerge.ExecuteGroup(dataTable);
        //Unhooks the event after mail merge execution.
        document.MailMerge.MergeField -= new MergeFieldEventHandler(MergeField_EmployeeGraph);
        //Creates file stream.
        using (FileStream outputStream = new FileStream(Path.GetFullPath(@"../../../Result.docx"), FileMode.Create, FileAccess.ReadWrite))
        {
            //Saves the Word document to file stream.
            document.Save(outputStream, FormatType.Docx);
        }
    }
}
  1. Use the following helper method to replace merge field with chart while performing mail merge by using MergeFieldEventHandler.

C#

private static void MergeField_EmployeeGraph(object sender, MergeFieldEventArgs args)
{
    //Creates chart based on the field value and insert into the Word document.
    if (args.FieldName == "GraphDetails")
    {
        //Gets their owner row.
        WParagraph paragraph = args.CurrentMergeField.OwnerParagraph;
        //Gets the field value.
        List<object[]> graphDetails = args.FieldValue as List<object[]>;
        //Creates the chart.
        WChart chart = CreateChart(paragraph.Document, graphDetails);
        int indexOfField = paragraph.ChildEntities.IndexOf(args.CurrentMergeField);
        //Clears the field;
        args.Text = string.Empty;
        //Inserts the chart at corresponding field location.
        paragraph.ChildEntities.Insert(indexOfField, chart);
    }
}
  1. Use the following helper methods and class to get employees data and create chart from the data.

C#

/// <summary>
/// Gets the employee data to perform mail merge. 
/// </summary>
public static List<Employees> GetEmployeeData()
{
    //Creates graph data for first employee.
    List<object[]> graphDetailsForEmployee1 = new List<object[]>();
    graphDetailsForEmployee1.Add(new object[] { "Month", "Highest Sale", "Average Sale", "Lowest Sale" });
    graphDetailsForEmployee1.Add(new object[] { "September", 67, 55, 12 });
    graphDetailsForEmployee1.Add(new object[] { "October", 74, 71, 70 });
    graphDetailsForEmployee1.Add(new object[] { "November", 81, 74, 60 });
    graphDetailsForEmployee1.Add(new object[] { "December", 96, 71, 20});
 
    //Creates graph data for the second employee.
    List<object[]> graphDetailsForEmployee2 = new List<object[]>();
    graphDetailsForEmployee2.Add(new object[] { "Month", "Highest Sale", "Average Sale", "Lowest Sale" });
    graphDetailsForEmployee2.Add(new object[] { "September", 100, 65, 50 });
    graphDetailsForEmployee2.Add(new object[] { "October", 72, 34, 15 });
    graphDetailsForEmployee2.Add(new object[] { "November", 150, 81, 63 });
    graphDetailsForEmployee2.Add(new object[] { "December", 91, 75, 50 });
 
    //Creates graph data for the third employee.
    List<object[]> graphDetailsForEmployee3 = new List<object[]>();
    graphDetailsForEmployee3.Add(new object[] { "Month", "Highest Sale", "Average Sale", "Lowest Sale" });
    graphDetailsForEmployee3.Add(new object[] { "September", 58, 26, 14 });
    graphDetailsForEmployee3.Add(new object[] { "October", 55, 45, 30 });
    graphDetailsForEmployee3.Add(new object[] { "November", 62, 51, 23 });
    graphDetailsForEmployee3.Add(new object[] { "December", 72, 45, 11 });
 
    //Adds all details in employee data collection for all employees.
    List<Employees> employeeData = new List<Employees>();
    employeeData.Add(new Employees("Nancy", "Davolio", "1", "505 - 20th Ave. E. Apt. 2A,", "Seattle", "USA", graphDetailsForEmployee1));
    employeeData.Add(new Employees("Andrew", "Fuller", "2", "908 W. Capital Way", "Tacoma", "USA", graphDetailsForEmployee2));
    employeeData.Add(new Employees("Margaret", "Peacock", "3", "4110 Old Redmond Rd.", "Redmond", "USA", graphDetailsForEmployee3));
    return employeeData;
}
 
/// <summary>
/// Creates the chart based on the graph data.
/// </summary>
private static WChart CreateChart(WordDocument document, List<object[]> graphDetails)
{
    //Create the new chart.
    WChart chart = new WChart(document);
    chart.Width = 410;
    chart.Height = 250;
    chart.ChartType = OfficeChartType.Column_Clustered;
    //Assign data.
    AddChartData(chart, graphDetails);
    //Set a chart title.
    chart.ChartTitle = "Sales Report";
    //Set Datalabels.
    IOfficeChartSerie serie1 = chart.Series.Add("Highest Sale");
    //Set the data range of chart series – start row, start column, end row and end column.
    serie1.Values = chart.ChartData[2, 2, 5, 2];
    IOfficeChartSerie serie2 = chart.Series.Add("Average Sale");
    //Set the data range of chart series start row, start column, end row and end column.
    serie2.Values = chart.ChartData[2, 3, 5, 3];
    IOfficeChartSerie serie3 = chart.Series.Add("Lowest Sale");
    //Set the data range of chart series start row, start column, end row and end column.
    serie3.Values = chart.ChartData[2, 4, 5, 4];
    //Set the data range of the category axis.
    chart.PrimaryCategoryAxis.CategoryLabels = chart.ChartData[2, 1, 6, 1];
    //Set legend.
    chart.HasLegend = true;
    chart.Legend.Position = OfficeLegendPosition.Bottom;
    //Hiding major gridlines
    chart.PrimaryValueAxis.HasMajorGridLines = false;
    return chart;
}
 
/// <summary>
/// Set the values for the chart.
/// </summary>
private static void AddChartData(WChart chart, List<object[]> graphDetails)
{
    //Set the value for chart data.
    int rowIndex = 1;
    int colIndex = 1;
    //Get the value from the DataTable and set the value for chart data
    foreach (object[] row in graphDetails)
    {
        foreach (object value in row)
        {
            chart.ChartData.SetValue(rowIndex, colIndex, value);
            colIndex++;
            if (colIndex == 5)
            break;
        }
        colIndex = 1;
        rowIndex++;
    }
}
 
/// <summary>
/// Represents a class to maintain employee details.
/// </summary>
public class Employees
{
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmployeeID { get; set; }
        public string Address { get; set; }
        public string City { get; set; }    
        public string Country { get; set; }
        public List<object[]> GraphDetails { get; set; }
        public Employees(string firstName, string lastName, string employeeID, string address, string city, string country, List<object[]> graphDetails)
        {
            FirstName = firstName;
            LastName = lastName;
            EmployeeID = employeeID;
            Address = address;
            City = city; 
            Country = country;
            GraphDetails = graphDetails; 
        }
}

A complete working sample to replace merge field with chart using mail merge in Word document in C# can be downloaded from GitHub.

Input Word document as follows.Input document

By executing the program, you will get the output document as follows.

Output document 

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

Explore more about the rich set of Syncfusion Word Framework features.

See Also:

How to replace merge field with HTML string using Mail merge

How to perform mail merge in Word document using image from URL

Conclusion

I hope you enjoyed learning about how to replace merge field with chart in Word document using mail merge.

You can refer to our  ASP.NET Core DocIo’s feature tour page to know about its other groundbreaking feature representations. You can also explore our   ASP.NET Core DocIo documentation to understand how to present and manipulate data.

For current customers, you can check out our ASP.NET Core 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 ASP.NET Core DocIo and other ASP.NET Core components.

If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our support forumsDirect-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)
Please sign in to leave a comment
Access denied
Access denied