Search code examples
c#ms-wordopenxml

C# Populate word template with OpenXml


I would like to create a new Word document which is based on a template with content controls.

I need to fill those contents controls (text).

I only found how to generate a new Word document but not bases on a template.

Do you have any link or tutorial ?

Maybe am I wrong using OpenXml to fill a template ?

        // Create a Wordprocessing document. 
        using (WordprocessingDocument myDoc =
               WordprocessingDocument.Create("d:/dev/test.docx",
                             WordprocessingDocumentType.Document))
        {
            // Add a new main document part. 
            MainDocumentPart mainPart = myDoc.AddMainDocumentPart();
            //Create Document tree for simple document. 
            mainPart.Document = new Document();
            //Create Body (this element contains
            //other elements that we want to include 
            Body body = new Body();
            //Create paragraph 
            Paragraph paragraph = new Paragraph();
            Run run_paragraph = new Run();
            // we want to put that text into the output document 
            Text text_paragraph = new Text("Hello World!");
            //Append elements appropriately. 
            run_paragraph.Append(text_paragraph);
            paragraph.Append(run_paragraph);
            body.Append(paragraph);
            mainPart.Document.Append(body);
            // Save changes to the main document part. 
            mainPart.Document.Save();
        } 

Solution

  • Going OpenXML is the right approach, because you can manipulate documents without the need to have MS Word installed – think server scenarios. However, its learning curve is steep and tedious. In my humble opinion, the best way is to ask for a budget to purchase a 3rd party toolkit and focus on the business domain and not on OpenXML tweaks.

    In your example, you have a template in Word and want to update (merge) it with data. I have done this with Docentric Toolkit for some of our scenarios and it works very well. Once you understand the basics of how it works you create solutions quickly. If you get stuck guys at DT won’t let you down. See this link (http://www.codeproject.com/Articles/759408/Creating-Word-documents-in-Net-using-Docentric-Too) to get the idea on how you can use it. By default it creates .docx, but you can get fixed final documents (pdf or xps) as well.