Populating Word 2007 Templates Through Open XML

I recently had a client at work interested in populating contracts out of the information stored in their task tracking tool.  Today this is a manual process where the user opens up a Microsoft Word template and retypes the data points stored in their primary application.

I first looked at a few commercial options, and then got some recommendations from Microsoft to look deeper into the Open XML SDK and leverage the native XML formats of the Office 2007 document types.  I found a few articles and blog posts that explained some of the steps, but didn’t seem to find a single source of the whole end to end process.  So, I figured that I’d demonstrate the prototype solution that I built.

First, we need a Word 2007 document.  Because I’m not feeling particular frisky today, I will fill this document with random text using the ever-useful “=rand(9)” command to make Word put 9 random paragraphs into my document.

2009.12.23word01

Next, I switch to the Developer tab to find the Content Controls I want to inject into my document.  Don’t see the Developer tab?  Go here to see how to enable it.

2009.12.23word02

Now I’m going to sprinkle a few Text Content Controls throughout my document.  The text of each control should indicate the type of content that goes there.  For each content control on the page, select it and choose the Properties button on the ribbon so that you can provide the control with a friendly name. 

2009.12.23word03

At this point, I have four Content Controls in my document and each has a friendly title.  Now we can save and close the document. As you probably know by now, the Office 2007 document formats are really just zip files.  If you change the extension of our just-saved Word doc from .docx to .zip, you can see the fun inside.

2009.12.23word04

I looked a few options for manipulating the underlying XML content and finally ended up on the easiest way to update my Content Controls with data from outside.  First, download the Word 2007 Content Control Toolkit from CodePlex.  Then install and launch the application.  After browsing to our Word document, we see our friendly-named Content Controls in the list.

2009.12.23word05

You’ll notice that the XPath column is empty.  What we need to do next is define a Custom XML Part for this Word document, and tie the individual XML nodes to each Content Control.  On the right hand side of the Word 2007 Content Control Toolkit you’ll see a window that tells us that there are currently no custom XML parts in the document.

2009.12.23word06

The astute among you may now guess that I will click the “Click here to create a new one.”  I have smart readers.  After choosing to create a new part, I switched to the Edit view so that I could easily hand craft an XML data structure.

2009.12.23word07

For a more complex structure, I could have also uploaded an existing XML structure.  The values I put inside each XML node are the values that the Word document will display in each content control.  Switch to the Bind view and you should see a tree structure.

2009.12.23word08

Click each node, and then drag it to the corresponding Content Control.  When all four are complete, the XPath column in the Content Controls should be populated.

2009.12.23word09

Go ahead and save the settings and close the tool.  Now, if we once again peek inside our Word doc by changing it’s extension to .zip,  we’ll see a new folder called CustomXml that has our XML definition in there.

2009.12.23word10

For my real prototype I built a WCF service that created the Word documents out of the templates and loaded them into SharePoint.  For this blog post, I’ll resort to a Console application which reads the template and emits the resulting Word document to my Desktop.  You’ll get the general idea though.

If you haven’t done so already, download and install the Open XML Format SDK 1.0 from Microsoft.  After you’ve done that, create a new VS.NET Console project and add a reference to DocumentFormat.OpenXML.  Mine was found here: C:\Program Files\OpenXMLSDK\1.0.1825\lib\DocumentFormat.OpenXml.dll. I then added the following “using” statements to my console class.

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using System.Xml; using System.IO;

Next I have all the code which makes a copy of my template, loads up the Word document, removes the existing XML part, and adds a new one which has been populated with the values I want within the Content Controls.

static void Main(string[] args)
        {

            Console.WriteLine("Starting up Word template updater ...");

            //get path to template and instance output
            string docTemplatePath = @"C:\Users\rseroter\Desktop\ContractSample.docx";
            string docOutputPath = @"C:\Users\rseroter\Desktop\ContractSample_Instance.docx";

            //create copy of template so that we don't overwrite it
            File.Copy(docTemplatePath , docOutputPath);

            Console.WriteLine("Created copy of template ...");

            //stand up object that reads the Word doc package
            using (WordprocessingDocument doc = WordprocessingDocument.Open(docOutputPath, true))
            {
                //create XML string matching custom XML part
                string newXml = "<root>" +
                    "<Location>Outer Space</Location>" +
                    "<DocType>Contract</DocType>" +
                    "<MenuOption>Start</MenuOption>" +
                    "<GalleryName>Photos</GalleryName>" +
                    "</root>";

                MainDocumentPart main = doc.MainDocumentPart;
                main.DeleteParts<CustomXmlPart>(main.CustomXmlParts);

                //add and write new XML part
                CustomXmlPart customXml = main.AddNewPart<CustomXmlPart>();
                using (StreamWriter ts = new StreamWriter(customXml.GetStream()))
                {

                    ts.Write(newXml);
                }

            //closing WordprocessingDocument automatically saves the document
            }

            Console.WriteLine("Done");
            Console.ReadLine();
        }

When I run the console application, I can see a new file added to my Desktop, and when I open it, I find that my Content Controls now have the values that I set from within my Console application.

2009.12.23word11

Not bad.  So, as you can imagine, it’s pretty simple to now take this Console app, and turn it into a service which takes in an object containing the data points we want added to our document.  So while this is hardly a replacement for a rich content management or contract authoring tool, it is a quick and easy way to do a programmatic mail merge and update existing documents.  Heck, you could even call this from a BizTalk application or custom application to generate documents based on message payloads.  Fun stuff.

Share

Author: Richard Seroter

Richard Seroter is currently the Chief Evangelist at Google Cloud and leads the Developer Relations program. He’s also an instructor at Pluralsight, a frequent public speaker, the author of multiple books on software design and development, and a former InfoQ.com editor plus former 12-time Microsoft MVP for cloud. As Chief Evangelist at Google Cloud, Richard leads the team of developer advocates, developer engineers, outbound product managers, and technical writers who ensure that people find, use, and enjoy Google Cloud. Richard maintains a regularly updated blog on topics of architecture and solution design and can be found on Twitter as @rseroter.

37 thoughts

  1. Looks like Erik beat me to the question – but I also think this seems to be the feature that is being removed in Word. Are we correct?

  2. Hi Richard, i am getting this error when compiled “The type ‘DocumentFormat.OpenXml.Packaging.CustomXmlPart’ must be convertible to ‘DocumentFormat.OpenXml.Packaging.IFixedContentTypePart’ in order to use it as parameter ‘T’ in the generic type or method ‘DocumentFormat.OpenXml.Packaging.OpenXmlPartContainer.AddNewPart()'”. Can u please help me where i am wrong.

  3. I have been searching for almost 2 days to find a simple example on how to use an excel list to populate choices for a drop-down list in word 2007. I really think you may have the answer above – but after downloading the Content Control ToolKit I have no prompt to install and launch – nor can i find it anywhere. I would love to proceed with your example… can u help???

    Desperately seeking answers…

    Madelyn

  4. Madelyn,
    I seem to recall some challenges there. I had to download and watch where I put it since it was hard to find. I thought it ended up on the Start menu though, and it should produce an exe in the Program Files directory. You have neither?

  5. I modified the code to use SDK 2.0

    CustomXmlPart customXml = mainPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);
    byte[] byteArray = Encoding.UTF8.GetBytes(newXml);
    MemoryStream stream = new MemoryStream(byteArray);
    customXml.FeedData(stream);

    And the Docx output file does not contain data defined in new Xml.

    Any clue?

  6. Hi,

    I have noticed strange behaviour! When I insert Rich text control in word document and then bind it to xml node using word content control toolkit – when I open the document in Word again – the control is PlainText !!!

    Don’t know if this has to do with Word or with Word CC toolkit…

  7. This is very interesting information, but i found it less useful for me. I want to create an XML Template to create a Help Document where i can define my styles and then use this template to send output to PDF file.

    I got very useful information from this post.

    Thanks a lot for help.

  8. Hi Richard,

    Great post.. and Thank you.

    I have a problem with the merged document. When we try to edit the content and save the merged document, the data is not saved. The merged data itself shows up.
    Even tried unchecking ‘Remove content control when contents are edited’ property (in the word template for a content control field). But doing so, none of the data was merged into the template.

    Can you please help me on this?
    KC

  9. Richard,

    After spending half a day staring at dcom config settings and trying to get word to automate creation of a template document working on a server (worked fine in my dev environment) I eventually thought there must be a better way nowadays.

    Of course there was and it is all here in your wonderful post, a couple of hours later and it’s all working using Open XML…. I owe you a pint 😉

    For v2 open XML SDK the only code change as already explained was to change this:
    CustomXmlPart customXml = main.AddNewPart();
    To this:
    CustomXmlPart customXml = main.AddCustomXmlPart(CustomXmlPartType.CustomXml);

    Much Karma,
    Mark.

  10. It was a really useful article and tutorial.

    I have a document with numbers in complex mode, but when I replace the content with numbers, it is formatted as Latin numbers. Is there way to assign a style for each control. I tried right clicking on content properties and checking ‘Use a style to format…’ but it was useless.

    Regards.

  11. Thank you for the great Post. I have the following question I don’t know if it’s possible to implement. In case a certain section is empty is there a possible way to hide the Content Control related to it.

  12. It is very interesting post. I took a somewhat different approach. I designed an app to generate Invoices as Word doc. I inserted bookmarks in a doc and used it as template. The made copy of the same and modified word doc, by locating the book marks and inserting the data . But this process is taking lot of time

  13. Thank you very much for this article! It’s been a time saver even some many years after its original posting. I was wondering if you or any other reader might know how to replace the static newXML text below:
    string newXml = “” +
    “Outer Space” +
    “Contract” +
    “Start” +
    “Photos” +
    “”;

    with a .xml file instead? So, I know what xml file I want to use and have an XSD, just not sure how to use the file instead of specifying the answers in code (e.g. “Outer Space”).

    I tried this, but it’s not populating the Word doc:
    string newXML =@”C:\Users\Christopher\Desktop\BookData\TestReport.xml”;

    Thanks
    Chris

    1. Was able to answer my own question, but thanks:

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using DocumentFormat.OpenXml;
      using DocumentFormat.OpenXml.Packaging;
      using DocumentFormat.OpenXml.Wordprocessing;
      using System.IO;

      namespace BookData
      {
      class Program
      {

      static void Main(string[] args)
      {
      string template = @”C:\Users\Christopher\Desktop\BookData\TestReportBeta.docx”;
      string outFile = @”C:\Users\Christopher\Desktop\BookData\TestReportBetaEND.docx”;
      string xmlPath = @”C:\Users\Christopher\Desktop\BookData\TestReport.xml”;

      // convert template to document
      File.Copy(template, outFile);

      using (WordprocessingDocument doc = WordprocessingDocument.Open(outFile, true))
      {
      MainDocumentPart mdp = doc.MainDocumentPart;
      if (mdp.CustomXmlParts != null)
      {
      mdp.DeleteParts(mdp.CustomXmlParts);
      }
      CustomXmlPart cxp = mdp.AddCustomXmlPart(CustomXmlPartType.CustomXml);
      FileStream fs = new FileStream(xmlPath, FileMode.Open);
      cxp.FeedData(fs);
      mdp.Document.Save();
      }
      }
      }
      }

      also here: http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/cd778b36-e003-4b96-bddb-c87d5b4b25eb/

  14. I have followed this tutorial exactly as stated accounting for the sdk 2.0 changes indicated in the comments:

    CustomXmlPart customXml = main.AddCustomXmlPart(CustomXmlPartType.CustomXml);

    I have created a simple docx file that contains a single content control called test1.
    Here is my xml:

    string newXml = “test2”;

    I am implementing this in a wcf web service that is opening the test docx file from SharePoint and then copying the file to a SharePoint document library after inserting the xml.

    Whenever I try to open the docx file that has been updated and copied, I get the following error:

    Microsoft Office cannot open this file because some parts are missing or invalid.

    Anyone have any thoughts on what could be wrong?

  15. If I open the file from the file system in a console application, it works properly. If I open the file in SharePoint from a wcf web service, I get the error indicated above.

    Here is my code for opening the docx file from SharePoint:


    SPFile sourceFile = myweb.GetFile(“/mylibrary/test1.docx”);

    using (Stream sourceFileStream = sourceFile.OpenBinaryStream())
    {
    using (WordprocessingDocument doc = WordprocessingDocument.Open(sourceFileStream, true))
    {

    Richard, you mentioned in your post that you implemented this in a wcf web service and SharePoint. Can you possibly post some code indicating how you did it? Did you open the source docx file from the file system or from a SharePoint document library?

  16. Nice tutorial. I’m writing a PHP- based XML parser to extract info from templated .docx files. This is a great place to understand how to use MS word to create custom XML namespaces for parsing later. Had to buy MS VS pro though to use this feature, which costs a bomb for individual developers. Wonder if there is a way to do it in VS express(free version).

  17. Hi, is it possible to do the same thing in your example, but without to pass by Word Content Control to append firstly a XML file. So, what I want to say, directly create a XML file and append it with C# code ?

    Thanks

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.