Manipulating dotx templates with C# [closed]
-
25-10-2019 - |
Question
I have a problem,
I have a .dotx file which has been supplied by customers. It contains a number of fields of different kinds added in developermode in Word.
I want to be able to use this dotx and fill it up with values.
How do I do this in C#-code?
Solution
The Microsoft OpemXML SDK allows you to manipulate docx/dotx files using c#. You can download the Microsoft OpenXML SDK from here.
You should first create a copy of your dotx file. Then find the fields/content palceholders in the template.
Here is a small example (using a simple word template with a rich text box content field):
// First, create a copy of your template.
File.Copy(@"c:\temp\mytemplate.dotx", @"c:\temp\test.docx", true);
using (WordprocessingDocument newdoc = WordprocessingDocument.Open(@"c:\temp\test.docx", true))
{
// Change document type (dotx->docx)
newdoc.ChangeDocumentType(WordprocessingDocumentType.Document);
// Find all structured document tags
IEnumerable<SdtContentRun> placeHolders = newdoc.MainDocumentPart.RootElement.Descendants<SdtContentRun>();
foreach (var cp in placeHolders)
{
var r = cp.Descendants<Run>().FirstOrDefault();
r.RemoveAllChildren(); // Remove children
r.AppendChild<Text>(new Text("my text")); // add new content
}
}
The example above is a very simple example. You have to adapt it to your word template structure.
Hope, this helps.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow