How to replace merge field with chart in Word document using mail merge?
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 a merge field with a chart using mail merge in a Word document in C#.
Steps to replace a merge field with a chart using mail merge in a Word document:
- Create a new C# .NET Core console application project.
- Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your .NET Core applications from NuGet.org.
- Include the following namespace in the Program.cs file.
C#
using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; using Syncfusion.OfficeChart;
- Use the following code example to replace a merge field with a chart using mail merge in a Word document.
C#
using (FileStream fileStream = new FileStream(Path.GetFullPath(@"../../../Template.docx"), FileMode.Open, FileAccess.ReadWrite)) { ///Loads an existing Word document into the DocIO instance.
using (WordDocument document = new WordDocument(fileStream, FormatType.Automatic))
{
//Gets the employee details as an “IEnumerable” collection.
List<Employees> employeeList = GetEmployeeData();
//Creates an instance of MailMergeDataTable by specifying the MailMerge group name and IEnumerable collection.
MailMergeDataTable dataTable = new MailMergeDataTable("Employees", employeeList);
//Uses the mail merge event handler to insert a 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 a file stream.
using (FileStream outputStream = new FileStream(Path.GetFullPath(@"../../../Result.docx"), FileMode.Create, FileAccess.ReadWrite))
{
//Saves the Word document to the file stream. document.Save(outputStream, FormatType.Docx); } } }
- Use the following helper method to replace a merge field with a chart while performing mail merge by using MergeFieldEventHandler.
C#
private static void MergeField_EmployeeGraph(object sender, MergeFieldEventArgs args) { //Creates a chart based on the field value and inserts it into the Word document.
if (args.FieldName == "GraphDetails")
{
//Gets its 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 the corresponding field location.
paragraph.ChildEntities.Insert(indexOfField, chart);
}
}
- Use the following helper methods and class to get employee data and create a chart from the data.
C#
/// <summary> /// Gets the employee data to perform mail merge. /// </summary> public static List<Employees> GetEmployeeData() { //Creates graph data for the 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 the 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) { //Creates the new chart.
WChart chart = new WChart(document);
chart.Width = 410;
chart.Height = 250;
chart.ChartType = OfficeChartType.Column_Clustered;
//Assigns data.
AddChartData(chart, graphDetails);
//Sets a chart title.
chart.ChartTitle = "Sales Report";
//Sets data labels.
IOfficeChartSerie serie1 = chart.Series.Add("Highest Sale");
//Sets 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");
//Sets 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");
//Sets the data range of chart series – start row, start column, end row, and end column.
serie3.Values = chart.ChartData[2, 4, 5, 4];
//Sets the data range of the category axis.
chart.PrimaryCategoryAxis.CategoryLabels = chart.ChartData[2, 1, 6, 1];
//Sets the legend.
chart.HasLegend = true;
chart.Legend.Position = OfficeLegendPosition.Bottom;
//Hides major gridlines.
chart.PrimaryValueAxis.HasMajorGridLines = false;
return chart;
}
/// <summary>
/// Sets the values for the chart.
/// </summary>
private static void AddChartData(WChart chart, List<object[]> graphDetails)
{
//Sets the value for chart data.
int rowIndex = 1;
int colIndex = 1;
//Gets the value from the DataTable and sets 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.
By executing the program, you will get the output document as follows.
Take a moment to peruse the documentation, where you can find 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, the PDF and Image conversions with code examples.
Explore more about the rich set of Syncfusion® Word Framework features.
See Also:
How to replace a merge field with an HTML string using Mail merge
How to perform mail merge in a Word document using an image from URL
Conclusion
I hope you enjoyed learning about how to replace a merge field with a chart in a Word document using mail merge.
You can refer to our ASP.NET Core DocIO’s feature tour page to know about its other groundbreaking features. 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 the comments below. You can also contact us through our support forums or feedback portal. We are always happy to assist you!