Versions Compared

Key

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

Intro

Excerpt

Emulate a Word mail merge using WordTemplate, featuring new nested repeat block technology.  A document will be created with each recipient's letter on a new page, complete with a nested table of orders. 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

Code Block
  public void GenerateDocument()
        {
            WordTemplate wt = new WordTemplate();
            wt.Open(@"..\..\WordTemplateFiles\NestedMailMergeTemplate.docx");
            //Retrieve the Data from the source, a csv file with a helper method
            DataTable dt = GetMailMergeData(@"..\..\WordData\NestedMailMergeData.csv");

            // set dt as the datasource for the repeatblock and "MailMerge" as the bookmark.
            // this will cause wordwriter to bind each letter on a different page of the output file.
            wt.SetRepeatBlock(dt, "MailMerge");
            wt.Process();
            //Save the Document in the desired location
            wt.Save(@"..\..\WordOutputFiles\NestedMailMerge_output.docx");
        }


        //Helper method to parse the csv files with data
        private DataTable GetMailMergeData(string csvFileName)
        {
            DataTable dt = new DataTable();
            using (GenericParserAdapter parser = new GenericParserAdapter(csvFileName))
            {
                parser.ColumnDelimiter = ',';
                parser.FirstRowHasHeader = true;

                dt = parser.GetDataTable();
            }
            return dt;
        }
    }

...