Page tree

Versions Compared


  • This line was added.
  • This line was removed.
  • Formatting was changed.



Generate a form letter with WordTemplate.

This demo's template document is in the format of a standard form letter.  The recipient and author information is inserted into the document dynamically.  You could also write the letter text and image into the document using WordTemplate.


Code Block
    public class FormLetterGenerator
        private string recipName, recipStreetAddr, recipCity,
            recipState, recipZip, authName, authTitle;
        /// <summary>
        /// Build the report with WordTemplate
        /// </summary>
        public void GenerateDocument()
            this.recipName = "Jon Smith";
            this.recipStreetAddr = "123 Main Street";
            this.recipCity = "Springfield";
            this.recipState = "CO";
            this.recipZip = "05555";
            this.authName = "Sarah White";
            this.authTitle = "CEO";
            // Form the required WordWriter name array.  The elements
            // in this array correspond to the names of the
            // merge fields in the template, and each element's array
            // index should correspond to an element in the value array
            string[] arrNames = {"RecipientName", "RecipientStreetAddr", "RecipientCity",
                                    "RecipientState", "RecipientZip", "AuthorName", "AuthorTitle"};
            // The value array.  The value of the elements in this array
            // contain info supplied in the web form. These values
            // represent the data that will be dynamically populated
            // in the template file.
            object[] arrValues = {recipName, recipStreetAddr, recipCity,
                                     recipState, recipZip, authName, authTitle};
            // Create the WordTemplate object
            WordTemplate wt = new WordTemplate();
            // Open the template document
            string templatePath = @"..\..\WordTemplateFiles\FormLetterTemplate.docx";
            // Set the datasource with the name and value arrays defined above
            wt.SetDataSource(arrValues, arrNames);
            // Process the template
            //Save the document in the desired location