I was recently tasked with building an add-on for a CRM application to allow the application to integrate with Microsoft Word and generate a mail merge.
I decided to use two examples for demonstrating how to generate the mail merge, the first will be from a Microsoft MSDN code sample and demonstrate a hard coded method of outputting data from my C# application to Microsoft Word.
For the second example, I'll demonstrate a more dynamic approach by connecting to a SQL sample database (Northwind). I'll build an ASP.NET user interface to allow selection and filtering of customers prior to sending the data to Microsoft Word for the mail merge.
Visual Studio 2010
Microsoft Word 2010
Microsoft SQL Server 2008R2
Microsoft Mail Merge Code - Here
Microsoft created some sample code for integrating custom c# applications with Microsoft Word and automating the mail merge, the code provides the mechanism for programmatically generating the mail merge with some inline customer data.
From Visual Studio 2010 I created a new ASP.NET project, the Microsoft code was developed with a Windows Forms application in mind but I ported it into an ASP.NET application. First I added a new reference to the project by expanding references from the solution explorer and selecting new reference. I selected the COM tab and chose the Microsoft Word 14 reference. This will add 2 new references to the project Microsoft.Office.Core and Microsoft.Office.Interop.Word.
Add a using statement for the newly added reference as follows:
using Word = Microsoft.Office.Interop.Word;
I cut the first four lines of the Microsoft code and pasted it at the beginning of the class declaration to ensure proper scope for these variables.
Next I switched to the design view of the default.aspx page in my project and clicked on the toolbox and added a new button to the current page.
Next I double clicked the new button and pasted the remainder of the code from the Microsoft article into the click event handler of the new button.
I built the application with no errors and launched it for a test.
I clicked the button and it looks like everything is working as expected so far, Microsoft Word launches and displays three customer forms that are ready to be printed/mailed.
The standard form data is consistent on all of the user forms and the inline unique customer information is populated into the variable field locations.
This example can be modified to read from a text or csv file or any number of methods that would allow an automated extraction of customer data.
The data can also be kept inline in the code behind as is.
This completes the first example, this example provides a good look into the Word object model and what it takes to programmatically create and manipulate Word objects. Again this is a pretty static and simple method for demonstrating the mail merge. A more advanced approach will be described in Part 2.
Continue to Part 2