Skip to content

Commit 9c8fa2d

Browse files
Merge pull request #391 from SyncfusionExamples/ES-833344-Sum-mergefield-values
ES-833344-Add the sample Sum-mergefield-values
2 parents 25dc121 + 1242224 commit 9c8fa2d

File tree

6 files changed

+173
-0
lines changed

6 files changed

+173
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio Version 16
4+
VisualStudioVersion = 16.0.31911.196
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sum-mergefield-values", "Sum-mergefield-values\Sum-mergefield-values.csproj", "{D3AF529E-DB54-4294-A876-DD42E1E472D0}"
7+
EndProject
8+
Global
9+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
10+
Debug|Any CPU = Debug|Any CPU
11+
Release|Any CPU = Release|Any CPU
12+
EndGlobalSection
13+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
14+
{D3AF529E-DB54-4294-A876-DD42E1E472D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15+
{D3AF529E-DB54-4294-A876-DD42E1E472D0}.Debug|Any CPU.Build.0 = Debug|Any CPU
16+
{D3AF529E-DB54-4294-A876-DD42E1E472D0}.Release|Any CPU.ActiveCfg = Release|Any CPU
17+
{D3AF529E-DB54-4294-A876-DD42E1E472D0}.Release|Any CPU.Build.0 = Release|Any CPU
18+
EndGlobalSection
19+
GlobalSection(SolutionProperties) = preSolution
20+
HideSolutionNode = FALSE
21+
EndGlobalSection
22+
GlobalSection(ExtensibilityGlobals) = postSolution
23+
SolutionGuid = {58137FF9-5AE1-4514-9929-3A8A7DA1DFEB}
24+
EndGlobalSection
25+
EndGlobal
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
{
2+
"Toplevel1":"1",
3+
"Reports":
4+
[
5+
{
6+
"Subject": "Maths",
7+
"Marks": "80"
8+
},
9+
{
10+
"Subject":"English",
11+
"Marks":"70"
12+
},
13+
{
14+
"Subject":"Science",
15+
"Marks":"82"
16+
}
17+
]
18+
}
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
using Newtonsoft.Json.Linq;
2+
using Syncfusion.DocIO;
3+
using Syncfusion.DocIO.DLS;
4+
using System;
5+
using System.Collections.Generic;
6+
using System.IO;
7+
8+
namespace Sum_mergefield_values
9+
{
10+
class Program
11+
{
12+
static int totalMarks = 0;
13+
static void Main(string[] args)
14+
{
15+
using (FileStream fileStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open))
16+
{
17+
//Loads an existing Word document.
18+
using (WordDocument wordDocument = new WordDocument(fileStream, FormatType.Automatic))
19+
{
20+
// Gets JSON object from JSON string.
21+
JObject jsonObject = JObject.Parse(File.ReadAllText(Path.GetFullPath(@"Data/ReportData.json")));
22+
// Converts to IDictionary data from JSON object.
23+
IDictionary<string, object> data = GetData(jsonObject);
24+
25+
//Creates the mail merge data table in order to perform mail merge
26+
MailMergeDataTable dataTable = new MailMergeDataTable("Reports", (List<object>)data["Reports"]);
27+
28+
//Uses the mail merge event handler to sum the field's values and set that value to the TotalMarks field during mail merge.
29+
wordDocument.MailMerge.MergeField += new MergeFieldEventHandler(MergeField_Event);
30+
31+
//Performs the mail merge operation with the dynamic collection
32+
wordDocument.MailMerge.ExecuteGroup(dataTable);
33+
34+
string[] fieldNames = new string[] { "TotalMarks" };
35+
string[] fieldValues = new string[] { "" };
36+
37+
//Performs the mail merge
38+
wordDocument.MailMerge.Execute(fieldNames, fieldValues);
39+
40+
//Saves the WOrd document file to file system.
41+
using (FileStream outputStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
42+
{
43+
wordDocument.Save(outputStream, FormatType.Docx);
44+
}
45+
}
46+
}
47+
}
48+
/// <summary>
49+
/// Event to sum the field's values and set that value to the TotalMarks field during mail merge.
50+
/// </summary>
51+
private static void MergeField_Event(object sender, MergeFieldEventArgs args)
52+
{
53+
54+
if (args.FieldName == "Marks")
55+
{
56+
//sum the Marks field values.
57+
totalMarks += Convert.ToInt32(args.FieldValue);
58+
}
59+
if (args.FieldName == "TotalMarks")
60+
{
61+
//Set sum of the Marks field values to the TotalMarks field;
62+
args.Text = totalMarks.ToString();
63+
}
64+
}
65+
66+
/// <summary>
67+
/// Gets array of items from JSON array.
68+
/// </summary>
69+
/// <param name="jArray">JSON array.</param>
70+
/// <returns>List of objects.</returns>
71+
private static List<object> GetData(JArray jArray)
72+
{
73+
List<object> jArrayItems = new List<object>();
74+
foreach (var item in jArray)
75+
{
76+
object keyValue = null;
77+
if (item is JObject)
78+
keyValue = GetData((JObject)item);
79+
jArrayItems.Add(keyValue);
80+
}
81+
return jArrayItems;
82+
}
83+
/// <summary>
84+
/// Gets data from JSON object.
85+
/// </summary>
86+
/// <param name="jsonObject">JSON object.</param>
87+
/// <returns>IDictionary data.</returns>
88+
private static IDictionary<string, object> GetData(JObject jsonObject)
89+
{
90+
Dictionary<string, object> dictionary = new Dictionary<string, object>();
91+
foreach (var item in jsonObject)
92+
{
93+
object keyValue = null;
94+
if (item.Value is JArray)
95+
keyValue = GetData((JArray)item.Value);
96+
else if (item.Value is JToken)
97+
keyValue = ((JToken)item.Value).ToObject<string>();
98+
dictionary.Add(item.Key, keyValue);
99+
}
100+
return dictionary;
101+
}
102+
}
103+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net8.0</TargetFramework>
6+
<RootNamespace>Sum_mergefield_values</RootNamespace>
7+
</PropertyGroup>
8+
9+
<ItemGroup>
10+
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
11+
<PackageReference Include="Syncfusion.DocIO.Net.Core" Version="*" />
12+
</ItemGroup>
13+
14+
<ItemGroup>
15+
<None Update="Data\ReportData.json">
16+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
17+
</None>
18+
<None Update="Data\Template.docx">
19+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
20+
</None>
21+
<None Update="Output\.gitkeep">
22+
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
23+
</None>
24+
</ItemGroup>
25+
26+
</Project>

0 commit comments

Comments
 (0)