Map Fields

This example demonstrates how to map mail merge fields.

Sometime we need to use pre defined templates , where we only have to change some minor things in order to make is a meaningfull word document file, this help us save time

We have a pre defined word document template with fields enclosed in special symbol "<< >>" which will be mapped to our database fields

All customers are populated from database .

User can choose any customer by clicking on the row selection, selected customer fields will be mapped to the fields in the document which are enclosed in "<< >>"

After clicking generate button it will launch a word document with fields mapped depending upon the customer selected above and the version of the word

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;

using OfficeComponent.Word;
using System.Data;
using System.Collections;

namespace OfficeComponent.Samples
{
    class MapFieldsExample : WordExampleBase
    {
        public DataRow row;

        public MapFieldsExample(string commonDataPath, string outputDir)
            : base(commonDataPath, outputDir)
        {

        }

        public MapFieldsExample(string commonDataPath, string outputDir, string xmlFile) : base(commonDataPath, outputDir, xmlFile)
        {

        }

        public override string Execute()
        {
#if WEB
            var table = MapFieldsExample.GetCustomers();
            row = table.Rows[0];
#endif

            if (row == null)
            {
                ShowError("Please select a row");
                return null;
            }

            // Open the Word template.
            WordDocument document = new WordDocument(CommonDataPath + "\\FollowUp.doc");

            // Merge Template fields with user entered data.
            document.MailMerge.RemoveEmptyParagraphs = true;

            // To clear the fields with empty value
            document.MailMerge.ClearFields = true;

            // Clear the map fields
            document.MailMerge.MappedFields.Clear();

            // Update the mapping fields
            document.MailMerge.MappedFields.Add("Contact Name", "ContactName");
            document.MailMerge.MappedFields.Add("Company Name", "CompanyName");

            document.MailMerge.Execute(row);

            string fileName = Path.Combine(OutputDir, this.GetType().Name + "_" + Guid.NewGuid().ToString() + GetExtension(SaveAsFormat));
            // Save the document.
            document.Save(fileName, SaveAsFormat);

            // Close the document.
            document.Close();

            return fileName;
        }

        #region Data Generation

        static Random random = new Random(Environment.TickCount);

        static string GetRandomAddress()
        {
            string[] list = new string[]
                                 {
                                     "Avda. de la Constitución 2222",
                                     "Mataderos 2312",
                                     "120 Hanover Sq.",
                                     "Berguvsvägen 8",
                                     "Forsterstr. 57",
                                     "24, place Kléber",
                                     "C/ Araquil, 67",
                                     "12, rue des Bouchers",
                                     "23 Tsawassen Blvd.",
                                     "Fauntleroy Circus",
                                 };

            return list[random.Next(list.Length)];
        }

        static string GetRandomName()
        {
            string[] list = new string[]
                                 {
                                     "Maria Anders",
                                     "Ana Trujillo",
                                     "Antonio Moreno",
                                     "Thomas Hardy",
                                     "Christina Berglund",
                                     "Hanna Moos",
                                     "Frédérique Citeaux",
                                     "Martín Sommer",
                                     "Laurence Lebihan",
                                     "Elizabeth Lincoln",
                                     "Victoria Ashworth",
                                     "Francisco Chang",
                                     "Yang Wang",
                                 };

            return list[random.Next(list.Length)];
        }

        static string GetRandomCompanyName()
        {
            string[] list = new string[]
                                 {
                                     "Alfreds Futterkiste",
                                     "Around the Horn",
                                     "Berglunds snabbköp",
                                     "Blauer See Delikatessen",
                                     "Bon app'",
                                     "Bottom-Dollar Markets",
                                     "B's Beverages",
                                     "Consolidated Holdings",
                                     "Ernst Handel",
                                     "Folies gourmandes",
                                     "Galería del gastrónomo",
                                     "Hanari Carnes",
                                     "Island Trading",
                                 };

            return list[random.Next(list.Length)];
        }

        static string GetRandonCity()
        {
            string[] list = new string[]
                                 {
                                     "Cork",
                                     "Cowes",
                                     "Versailles",
                                     "Vancouver",
                                     "Walla Walla",
                                     "Frankfurt a.M.",
                                     "San Francisco",
                                     "Barquisimeto",
                                     "Portland",
                                     "Bergamo",
                                     "Bruxelles",
                                     "Montréal",
                                     "Leipzig",
                                     "London",
                                 };

            return list[random.Next(list.Length)];
        }

        static string GetRandomCountry()
        {
            string[] list = new string[]
                                 {
                                     "Germany",
                                     "Venezuela",
                                     "USA",
                                     "Canada",
                                     "Belgium",
                                     "Italy",
                                     "Argentina",
                                     "UK",
                                     "France",
                                     "Mexico",
                                     "Austria",
                                     "Portugal",
                                     "Brazil",
                                     "Switzerland",
                                 };

            return list[random.Next(list.Length)];
        }

        static string GetRandomPostalCode()
        {
            string[] list = new string[]
                                 {
                                     "PO31 7PJ",
                                     "14776",
                                     "78000",
                                     "V3F 2K1",
                                     "99362",
                                     "94117",
                                     "3508",
                                     "24100",
                                     "B-1180",
                                     "SW7 1RZ",
                                     "99508",
                                     "50739",
                                     "05033",
                                     "02389-673",
                                 };

            return list[random.Next(list.Length)];
        }

        /// 
        /// Get fictitious customer list.
        /// 
        /// 
        internal static DataTable GetCustomers()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("CustomerID", typeof(int));
            dt.Columns.Add("CompanyName", typeof(string));
            dt.Columns.Add("ContactName", typeof(string));
            dt.Columns.Add("Address", typeof(string));
            dt.Columns.Add("City", typeof(string));
            dt.Columns.Add("PostalCode", typeof(string));
            dt.Columns.Add("Country", typeof(string));

            for (int i = 0; i < 50; i++)
            {
                dt.Rows.Add(1000 + i, GetRandomCompanyName(), GetRandomName(), GetRandomAddress(), GetRandonCity(), GetRandomPostalCode(), GetRandomCountry());
            }

            return dt;
        }

        #endregion
    }
}
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Text

Imports OfficeComponent.Word
Imports System.Collections

Namespace OfficeComponent.Samples
	Friend Class MapFieldsExample
		Inherits WordExampleBase
		Public row As DataRow

		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String)
			MyBase.New(commonDataPath, outputDir)

		End Sub

		Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String, ByVal xmlFile As String)
			MyBase.New(commonDataPath, outputDir, xmlFile)

		End Sub

		Public Overrides Function Execute() As String
#If WEB Then
			Dim table = MapFieldsExample.GetCustomers()
			row = table.Rows(0)
#End If

			If row Is Nothing Then
				ShowError("Please select a row")
				Return Nothing
			End If

			' Open the Word template.
			Dim document As New WordDocument(CommonDataPath & "\FollowUp.doc")

			' Merge Template fields with user entered data.
			document.MailMerge.RemoveEmptyParagraphs = True

			' To clear the fields with empty value
			document.MailMerge.ClearFields = True

			' Clear the map fields
			document.MailMerge.MappedFields.Clear()

			' Update the mapping fields
			document.MailMerge.MappedFields.Add("Contact Name", "ContactName")
			document.MailMerge.MappedFields.Add("Company Name", "CompanyName")

			document.MailMerge.Execute(row)

			Dim fileName As String = Path.Combine(OutputDir, Me.GetType().Name & "_" & Guid.NewGuid().ToString() & GetExtension(SaveAsFormat))
			' Save the document.
			document.Save(fileName, SaveAsFormat)

			' Close the document.
			document.Close()

			Return fileName
		End Function

		#Region "Data Generation"

		Private Shared random As New Random(Environment.TickCount)

		Private Shared Function GetRandomAddress() As String
			Dim list() As String = { "Avda. de la Constitución 2222", "Mataderos 2312", "120 Hanover Sq.", "Berguvsvägen 8", "Forsterstr. 57", "24, place Kléber", "C/ Araquil, 67", "12, rue des Bouchers", "23 Tsawassen Blvd.", "Fauntleroy Circus" }

			Return list(random.Next(list.Length))
		End Function

		Private Shared Function GetRandomName() As String
			Dim list() As String = { "Maria Anders", "Ana Trujillo", "Antonio Moreno", "Thomas Hardy", "Christina Berglund", "Hanna Moos", "Frédérique Citeaux", "Martín Sommer", "Laurence Lebihan", "Elizabeth Lincoln", "Victoria Ashworth", "Francisco Chang", "Yang Wang" }

			Return list(random.Next(list.Length))
		End Function

		Private Shared Function GetRandomCompanyName() As String
			Dim list() As String = { "Alfreds Futterkiste", "Around the Horn", "Berglunds snabbköp", "Blauer See Delikatessen", "Bon app'", "Bottom-Dollar Markets", "B's Beverages", "Consolidated Holdings", "Ernst Handel", "Folies gourmandes", "Galería del gastrónomo", "Hanari Carnes", "Island Trading" }

			Return list(random.Next(list.Length))
		End Function

		Private Shared Function GetRandonCity() As String
			Dim list() As String = { "Cork", "Cowes", "Versailles", "Vancouver", "Walla Walla", "Frankfurt a.M.", "San Francisco", "Barquisimeto", "Portland", "Bergamo", "Bruxelles", "Montréal", "Leipzig", "London" }

			Return list(random.Next(list.Length))
		End Function

		Private Shared Function GetRandomCountry() As String
			Dim list() As String = { "Germany", "Venezuela", "USA", "Canada", "Belgium", "Italy", "Argentina", "UK", "France", "Mexico", "Austria", "Portugal", "Brazil", "Switzerland" }

			Return list(random.Next(list.Length))
		End Function

		Private Shared Function GetRandomPostalCode() As String
			Dim list() As String = { "PO31 7PJ", "14776", "78000", "V3F 2K1", "99362", "94117", "3508", "24100", "B-1180", "SW7 1RZ", "99508", "50739", "05033", "02389-673" }

			Return list(random.Next(list.Length))
		End Function

		''' 
		''' Get fictitious customer list.
		''' 
		''' 
		Friend Shared Function GetCustomers() As DataTable
			Dim dt As New DataTable()
			dt.Columns.Add("CustomerID", GetType(Integer))
			dt.Columns.Add("CompanyName", GetType(String))
			dt.Columns.Add("ContactName", GetType(String))
			dt.Columns.Add("Address", GetType(String))
			dt.Columns.Add("City", GetType(String))
			dt.Columns.Add("PostalCode", GetType(String))
			dt.Columns.Add("Country", GetType(String))

			For i As Integer = 0 To 49
				dt.Rows.Add(1000 + i, GetRandomCompanyName(), GetRandomName(), GetRandomAddress(), GetRandonCity(), GetRandomPostalCode(), GetRandomCountry())
			Next i

			Return dt
		End Function

		#End Region
	End Class
End Namespace