Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Mail-Merge/Sum-mergefield-values/.NET/Sum-mergefield-values.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31911.196
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sum-mergefield-values", "Sum-mergefield-values\Sum-mergefield-values.csproj", "{D3AF529E-DB54-4294-A876-DD42E1E472D0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D3AF529E-DB54-4294-A876-DD42E1E472D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D3AF529E-DB54-4294-A876-DD42E1E472D0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D3AF529E-DB54-4294-A876-DD42E1E472D0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D3AF529E-DB54-4294-A876-DD42E1E472D0}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {58137FF9-5AE1-4514-9929-3A8A7DA1DFEB}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"Toplevel1":"1",
"Reports":
[
{
"Subject": "Maths",
"Marks": "80"
},
{
"Subject":"English",
"Marks":"70"
},
{
"Subject":"Science",
"Marks":"82"
}
]
}
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

103 changes: 103 additions & 0 deletions Mail-Merge/Sum-mergefield-values/.NET/Sum-mergefield-values/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
using Newtonsoft.Json.Linq;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using System;
using System.Collections.Generic;
using System.IO;

namespace Sum_mergefield_values
{
class Program
{
static int totalMarks = 0;
static void Main(string[] args)
{
using (FileStream fileStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open))
{
//Loads an existing Word document.
using (WordDocument wordDocument = new WordDocument(fileStream, FormatType.Automatic))
{
// Gets JSON object from JSON string.
JObject jsonObject = JObject.Parse(File.ReadAllText(Path.GetFullPath(@"Data/ReportData.json")));
// Converts to IDictionary data from JSON object.
IDictionary<string, object> data = GetData(jsonObject);

//Creates the mail merge data table in order to perform mail merge
MailMergeDataTable dataTable = new MailMergeDataTable("Reports", (List<object>)data["Reports"]);

//Uses the mail merge event handler to sum the field's values and set that value to the TotalMarks field during mail merge.
wordDocument.MailMerge.MergeField += new MergeFieldEventHandler(MergeField_Event);

//Performs the mail merge operation with the dynamic collection
wordDocument.MailMerge.ExecuteGroup(dataTable);

string[] fieldNames = new string[] { "TotalMarks" };
string[] fieldValues = new string[] { "" };

//Performs the mail merge
wordDocument.MailMerge.Execute(fieldNames, fieldValues);

//Saves the WOrd document file to file system.
using (FileStream outputStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
wordDocument.Save(outputStream, FormatType.Docx);
}
}
}
}
/// <summary>
/// Event to sum the field's values and set that value to the TotalMarks field during mail merge.
/// </summary>
private static void MergeField_Event(object sender, MergeFieldEventArgs args)
{

if (args.FieldName == "Marks")
{
//sum the Marks field values.
totalMarks += Convert.ToInt32(args.FieldValue);
}
if (args.FieldName == "TotalMarks")
{
//Set sum of the Marks field values to the TotalMarks field;
args.Text = totalMarks.ToString();
}
}

/// <summary>
/// Gets array of items from JSON array.
/// </summary>
/// <param name="jArray">JSON array.</param>
/// <returns>List of objects.</returns>
private static List<object> GetData(JArray jArray)
{
List<object> jArrayItems = new List<object>();
foreach (var item in jArray)
{
object keyValue = null;
if (item is JObject)
keyValue = GetData((JObject)item);
jArrayItems.Add(keyValue);
}
return jArrayItems;
}
/// <summary>
/// Gets data from JSON object.
/// </summary>
/// <param name="jsonObject">JSON object.</param>
/// <returns>IDictionary data.</returns>
private static IDictionary<string, object> GetData(JObject jsonObject)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
foreach (var item in jsonObject)
{
object keyValue = null;
if (item.Value is JArray)
keyValue = GetData((JArray)item.Value);
else if (item.Value is JToken)
keyValue = ((JToken)item.Value).ToObject<string>();
dictionary.Add(item.Key, keyValue);
}
return dictionary;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>Sum_mergefield_values</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Syncfusion.DocIO.Net.Core" Version="*" />
</ItemGroup>

<ItemGroup>
<None Update="Data\ReportData.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Data\Template.docx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Output\.gitkeep">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
Loading