Page tree

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.

...

Code Block
 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 = wt.Open(@"..\..\WordTemplateFiles\MailMergeTemplateNestedMailMergeTemplate.docx";
            wt.Open(templatePath);
             //Retrieve Get the datatableData forfrom anythe statesource, bya parsingcsv thatfile state'swith specifica csvhelper filemethod
            DataTable RegionDatadt = GetCustomerDataGetMailMergeData(@"..\..\WordData\MailMergeDemoData"+this.stateCode+".CSV"NestedMailMergeData.csv");

             // Setset thedt DataTable as the sourcedatasource for the mailmerge.repeatblock and "MailMerge" as          wt.SetMailMerge(RegionData);the bookmark.
            wt.Process();

            // Save the document
// this will cause wordwriter to bind each letter on a different page of the output file.
           string docName = String.Format("MailMerge-{0}", this.stateCodewt.SetRepeatBlock(dt, "MailMerge");
            wt.Save(@"..\..\WordOutputFiles\"+ docName+ "_output"+".docx"Process();
        }          /// <summary>
        /// Parses the data fromSave the Document in the csvdesired filelocation
with the data for a specific state      wt.Save(@"..\..\WordOutputFiles\NestedMailMerge_output.docx");
  /// Note: only the MA csvfile exists}
because
this
is for sample purposes         ///Helper </summary>method to parse the csv files with data
 /// <returns>DataTable of mailing data</returns>         private DataTable GetCustomerDataGetMailMergeData(Stringstring csvFileName)
        {
            DataTable dt = new DataTable();
            using (GenericParserAdapter parser = new GenericParserAdapter(csvFileName))
            {
                parser.ColumnDelimiter = ',';
                parser.FirstRowHasHeader = true;

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

 Downloads

Panel

 Template: NestedMailMergeTemplate.docx

Data: NestedMailMergeData.csv

Output:  NestedMailMerge_output.docx