Table of Contents
Hello World with WordTemplate
WordWriter's WordTemplate approach allows you to write data to a template file that contains merge field. The merge fields tell WordWriter where to bind specific sets of data, similar to Word's mail merge. This tutorial will show you the basics on how to dynamically insert data into a document using WordTemplate by taking custom text from a web form textbox and inserting it into a template file.
Setting up the template file
Create a new .docx file. Save it as template.docx.
Go to the Insert tab on the ribbon > Text group > Quick Parts drop-down. Select Field.
In the Field dialog, select Mergefield from the Field names list.
In the Field Properties section, type "Variable" in the Field name box. Click OK.
This will create a merge field <<Variable>> which will correspond to a column in a data set with only one row of data.
The template is now complete. We'll move on to writing the code to bind the data to this merge field.
Writing the Code
Include the SoftArtisans.OfficeWriter.WordWriter namespace in the code behind.
Instantiate the WordTemplate object.
Open the template file with WordTemplate.Open
In this example, we'll pull a text value from a textbox on a web form that a user submitted. Get the data value from the web form's text box
Create an object array to hold the textbox value. Create a string array to hold the column name "Variable"
Use WordTemplate.SetDataSource to bind the data to template file.
WordTemplate has three methods to bind data: WordTemplate.SetDataSource, WordTemplate.SetRepeatBlock, and WordTemplate.SetMailMerge. SetDataSource binds a single row of data to the template, where the merge fields can span the entire document. To bind a single value or group of single values, you need to put those in a data set, such as an array and then bind that array to the template file.
Call WordTemplate.Process() to bind the data to the template file.
Save the output with WordTemplate.Save
There are several options for WordTemplate.Save including: save to disk, save to memory stream, stream back to the client inline, and stream back to the client as an attachment. In this case, we're streaming the document back to the client as an attachment.
Run your code.
In the output file you will see that the merge field has been replaced by the value.
Congratulations, you completed Hello World using WordTemplate!
You can download the code for the Hello World tutorial as a Visual Studio solution.