Intro

Emulate a Word mail merge using WordTemplate.  A document will be created with each recipient's letter on a new page. Take care of all of your mail merge production with one print job.


Letters will be created for a selection of customers in the database.  This demo uses Nested Repeat Blocksthat signal WordTemplate to only repeat specific sections of the document when appropriate. This way we can create complex documents with dynamically generated tables with only a single database query and one call to SetRepeatBlock.

Note that using nested repeat blocks is only supported by using docx files.

Code

  

   
 private string stateCode;


 public void GenerateDocument()
        {
            //Select the state for which we will print out the data
            this.stateCode = "MA";
            // Create WordTemplate
            WordTemplate wt = new WordTemplate();
 
            // Open the template document
            string templatePath = @"..\..\WordTemplateFiles\MailMergeTemplate.docx";
            wt.Open(templatePath);
     
            // Get the datatable for any state by parsing that state's specific csv file
            DataTable RegionData = GetCustomerData(@"..\..\WordData\MailMergeDemoData"+this.stateCode+".CSV");
           
          
            // Set the DataTable as the source for the mailmerge.
            wt.SetMailMerge(RegionData);
            wt.Process();
      
            // Save the document
            string docName = String.Format("MailMerge-{0}", this.stateCode);
            wt.Save(@"..\..\WordOutputFiles\"+ docName+ "_output"+".docx");
        }

        /// <summary> 
        /// Parses the data from the csv file with the data for a specific state
        /// Note: only the MA csvfile exists because this is for sample purposes
        /// </summary>
        /// <returns>DataTable of mailing data</returns>
        private DataTable GetCustomerData(String csvFileName)
        {
            DataTable dt;
            using (GenericParserAdapter parser = new GenericParserAdapter(csvFileName))
            {
                parser.ColumnDelimiter = ',';
                parser.FirstRowHasHeader = true;
                
                dt = parser.GetDataTable();
            }
            return dt;
        }

 

 Downloads

 Template:  MailMergeTemplate.docx

Data: MailMergeDemoDataMA.csv

 Output:  MailMerge-MA_output.docx