Generating Open XML Documents using T4 Text Templates

This is a fun project that I’ve been meaning to do for some time – and I finally found the time in the last week.  T4 Text Templates are a very cool technology in Visual Studio 2008 and 2010 that make it super-easy to generate C# code, XML, or other text in an automated fashion as part of the editing experience in Visual Studio.  The way they work is that you write a text template that consists of a mixture of text and code.  The text can be C# code, XML, HTML, or just about any kind of text that you can imagine.  The code can be C# or VB.NET – the code is embedded in special code blocks that are delimited by <# and #>.  Then, when you save the template in Visual Studio, at that point in time, right as you save it, Visual Studio transforms the template into a complete program, compiles it, runs it, and then saves the output in a file in your project.

This is a natural technology to apply to Open XML document generation. In this video, I create a text template from some LINQ to XML code, and a word-processing document that I saved in the Flat OPC format.  When you save the template, it generates automatically a word-processing document from the template.  You can open the word-processing document immediately after saving the template.

While it is great to edit and develop T4 templates in Visual Studio 2010, you may want to generate a document in a different context – perhaps as part of a larger process.  You can write your own T4 template processor by writing a ‘Custom Host’.  The video walks through this process and demonstrates generating a word-processing document from a command line program.  Note that before you can build a Custom Host, you need to install the Visual Studio 2010 SDK.

I kept the actual document that I generate as simple as possible, as I was more concerned about demonstrating the mechanics of using T4 templates to generate Open XML documents.  You can take these basic ideas that I present in this video, and generate some really complicated documents with a minimum of effort.

I’ve attached the code to this post.

One last point – as I mentioned earlier in this post, in the video, I show generating a Flat OPC document.  It is pretty simple to convert that Flat OPC document to an ordinary DOCX.  The blog post, Transforming Flat OPC Format to Open XML Documents, shows how.

T4 templates are cool.  I hope you enjoy watching this video as much as I enjoyed making it.

Download – Example Code

-Eric