Hi, I'm Ray

09 Feb, 2019

Generating DOCX (MS Word) documents programmatically using a template (Rework)

Programming, .NET, C#, MS Word

This is a follow up to a post I wrote last year, Generating MS Word documents programmatically using placeholders in a template.

This was about generating MS Word (docx) documents by using find-and-replaceable tokens in an existing (template) document. In the previous post I shared some code and explained my thinking on the subject. However, at the time, the code made use of a temporary directory and wasn’t precisely read to use.

In this update, I’ve reworked the code into a class and done away with writing data to a temporary file and all that business.

Okay, let’s get started.


string filename = @"C:\template.docx";
string saveFilename = @"C:\new-file.docx";

Docxument doc = new Docxument(filename);
doc.ReplacementWords.Add("%title%", "Mr");
doc.ReplacementWords.Add("%firstname%", "John");
doc.ReplacementWords.Add("%familyname%", "Smith");			

var work1 = new Dictionary();
work1.Add("%title%", "Student");
work1.Add("%company%", "University");

var work2 = new Dictionary();
work2.Add("%title%", "Graduate");
work2.Add("%company%", "First Company");

doc.ReplacementParagraphs.Add("%work_experience%", new List>()



The code

Source Code