-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMain.cs
66 lines (52 loc) · 2.05 KB
/
Main.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
class Program
{
static void Main()
{
string filePath = "templateletter.docx";
using (WordprocessingDocument document = WordprocessingDocument.Open(filePath, true))
{
string[] templateFields = GetTemplateFields(document);
Dictionary<string, string> fieldValues = new Dictionary<string, string>
{
{ "Name", "Julie" },
{ "count", "20" },
{ "sender", "Miguel" }
};
PopulateDocumentFields(document, fieldValues);
}
}
static string[] GetTemplateFields(WordprocessingDocument document)
{
List<string> fieldNames = new List<string>();
{
MainDocumentPart mainPart = document.MainDocumentPart;
IEnumerable<BookmarkStart> fields = mainPart.RootElement.Descendants<BookmarkStart>();
foreach (BookmarkStart field in fields)
{
string fieldName = field.Name;
fieldNames.Add(fieldName);
}
}
return fieldNames.ToArray();
}
static void PopulateDocumentFields(WordprocessingDocument document, Dictionary<string, string> fieldValues)
{
MainDocumentPart mainPart = document.MainDocumentPart;
var textElements = mainPart.RootElement.Descendants<Text>();
foreach (var fieldValue in fieldValues)
{
string fieldName = fieldValue.Key;
string value = fieldValue.Value;
var matchedField = mainPart.RootElement.Descendants<BookmarkStart>()
.FirstOrDefault(b => { return b?.Name == fieldName; });
var textField = matchedField.NextSibling().NextSibling().NextSibling().Descendants<Text>().FirstOrDefault();
if (textField != null)
{
textField.Text = value;
}
}
document.SaveAs("editedDoc.docx");
}
}