Page tree

Versions Compared

Key

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

...

This part of the tutorial will cover how to set up the WordTemplate code to bind the data to the template. This assumes a basic knowledge of WordTemplate and how to bind data to Word templates.

1. Include the SoftArtisans.OfficeWriter.WordWriter namespace in the code behind

Code Block

using SoftArtisans.OfficeWriter.WordWriter;

2. Create a new WordTemplate object and open the template file.

Code Block

WordTemplate WT = new WordTemplate();
WT.Open(Page.MapPath("//templates//Business_Label_template.docx"));

3. Get the employee data for the business labels.

Info
titleFollowing the Sample Code

In the sample project, we are parsing CSV files with query results, rather than querying a live database. The CSV files are available under the data directory. There is a copy of the CSV parser, GenericParsing.dll in the bin directory of the project. The helper method GetCSVData is defined in Part1.aspx.cs in a region marked Utility Methods.

This call is to a helper method GetCSVData that parses the CSV files and returns a DataTable with the values.

Code Block

DataTable dtBusinessLabels = GetCSVData("//data//BusinessLabelTutorialData.csv");

4. Use WordTemplate.SetMailMerge to bind the employee data to the template.

Recall that SetMailMerge treats the entire document as a repeat block. This means that the merge fields in the document will need to match the column names of the data source. If there are any stray merge fields in the document, WordWriter will throw an error.

Code Block

WT.SetMailMerge(dtBusinessLabels);

5. Process and save the template file.

Code Block

WT.Process();
WT.Save(Page.Response, "Business_Label_Output.docx", false);

The completed code should look like this:

Code Block

//Instantiate a new WordTemplate object
WordTemplate WT = new WordTemplate();

//Open the template file
WT.Open(Page.MapPath("//templates//Business_Label_template.docx"));

//Get the order info datatable using GenericParser
DataTable dtBusinessLabels = GetCSVData("//data//BusinessLabelTutorialData.csv");

//Set the data sources to import a single row of data for each source
WT.SetMailMerge(dtBusinessLabels);

//Process to import the data to the template
WT.Process();

WT.Save(Page.Response, "Business_Labels_Output.docx", false);

Run the code. You will notice that each employee has a page of business label's with that particular employee's data.

Image Added

This is the intended SetMailMerge behavior, as the entire document was repeated for each row of data. In the next section we will incorporate next fields so that only one business label is made for each employee.

Adding NEXT fields

Final Code

...