Thursday, 17 August 2017 07:19

Identify Merge Field Names in Word with C#

We often come across a scenario where we need to merge data to the merge fields which are created by some others, and we are not sure about the merge fields’ names. So in order to accomplish the mail merge purpose, first we need to read the names of all the merge fields.

The MailMerge class in Spire.Doc.Reporting namespace exposes the following methods which return a collection of merge field names or group (region) names in a word document.

  • public string[] GetMergeFieldNames(): return a collection of all the merge field names.
  • public string[] GetMergeFieldNames(string groupName): return a collection of merge field names within a specific group.
  • public string[] GetMergeGroupNames(): return a collection of group names.

For better demonstration, we use the following sample document:

Identify Merge Field Names in Word with C#

The following example elaborates how to read the names of groups and merge fields in above word document.

using Spire.Doc;
using System;
namespace MailMerge
{
    class Program
    {
        static void Main(string[] args)
        {

            //Creates Document instance
            Document document = new Document();

            //Loads the word document
            document.LoadFromFile("MergeFields.docx");

            //Gets the collection of group names
            string[] GroupNames = document.MailMerge.GetMergeGroupNames();

            //Gets the collection of merge field names in a specific group
            string[] MergeFieldNamesWithinRegion = document.MailMerge.GetMergeFieldNames("Products");

            // Gets the collection of all the merge field names
            string[] MergeFieldNames = document.MailMerge.GetMergeFieldNames();

            Console.WriteLine("----------------Group Names-----------------------------------------");
            for (int i = 0; i < GroupNames.Length; i++)
            {
                Console.WriteLine(GroupNames[i]);
            }

            Console.WriteLine("----------------Merge field names within a specific group-----------");
            for (int j = 0; j < MergeFieldNamesWithinRegion.Length; j++)
            {
                Console.WriteLine(MergeFieldNamesWithinRegion[j]);
            }

            Console.WriteLine("----------------All of the merge field names------------------------");
            for (int k = 0; k < MergeFieldNames.Length; k++)
            {
                Console.WriteLine(MergeFieldNames[k]);
            }

        }

    }
}

Screenshot:

Identify Merge Field Names in Word with C#

Published in Mail Merge
Friday, 12 May 2017 01:59

Creating Mail Merge for a group in C#

In Spire.Doc, we can use mail merge to insert multiple records from data source to a specified region in a Word template document. The region must be marked by two merge fileds with special names like «GroupStart:GroupName» and «GroupEnd:GroupName», where GroupStart and GroupEnd means the start and end point of a group, it's also the start and end point of the region. After performing Mail merge, the region gets repeated for every record from the data source.

For better demonstration, we created a template document with merge fields as follows:

Creating Mail Merge for a group in C#

In this template, "Products" is the group name and we should use the same name when executing mail merge using code. The merge fileds “GroupStart:Products” and “GroupEnd:Products” mean the start and end of the group and the region.

Code snippets:

At first, we defined a class named "Product", in which we created a constructor Product (int number, string type, string name, string price, string vendor, string expirydate) and added four properties "Number", "Type", "Name", "Price", "Vendor" and "ExpiryDate".

Step 1: Instantiate two objects of the Product class and add them into a list.

Product p1 = new Product(1, "Software", "Spire.Doc", "$799", "E-iceblue", "April 28th,2018");
Product p2 = new Product(2, "Software", "Spire.PDF", "$599", "E-iceblue", "September 15th,2017");
            
List<Product> list = new List<Product>();
list.Add(p1);
list.Add(p2);

Step 2: Load the template document.

Document document = new Document("ProductsList.docx");

Step 3: Use the list as data source and execute Mail merge for the group "Products".

MailMergeDataTable table = new MailMergeDataTable("Products", list);           
document.MailMerge.ExecuteGroup(table);

Step 4: Save the document.

document.SaveToFile("Output.docx");

After executing above code, we will get the resultant document as follows:

Creating Mail Merge for a group in C#

Full codes:

using Spire.Doc;
using Spire.Doc.Reporting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MailMerge
{
    class Program
    {
        static void Main(string[] args)
        {
            Product p1 = new Product(1, "Software", "Spire.Doc", "$799", "E-iceblue", "April 28th,2018");
            Product p2 = new Product(2, "Software", "Spire.PDF", "$599", "E-iceblue", "September 15th,2017");

            List list = new List();
            list.Add(p1);
            list.Add(p2);

            Document document = new Document("ProductsList.docx");

            MailMergeDataTable table = new MailMergeDataTable("Products", list);
            document.MailMerge.ExecuteGroup(table);

            document.SaveToFile("Output.docx");
        }
    }


    public class Product
    {
        public Product(int number, string type, string name, string price, string vendor, string expirydate)
        {
            this.Number = number;
            this.Type = type;
            this.Name = name;
            this.Price = price;
            this.Vendor = vendor;
            this.ExpiryDate = expirydate;
        }

        public int Number { get; set; }
        public string Type { get; set; }
        public string Name { get; set; }
        public string Price { get; set; }
        public string Vendor { get; set; }
        public string ExpiryDate { get; set; }
    }
    
}
Published in Mail Merge
Tuesday, 27 September 2016 03:47

How to use mail merge to merge the image value

Last article we have shown how to create the mail merge template and merge the text value to it by using Spire.Doc. As we know that, besides the text value, we also use the mail merge feature to merge the image value too. This article will demonstrate how to merge the image value to the mail merge template in C#.

Here comes to the details of how use the mail merge to merge the image value. Firstly, please view the mail merge template and the image later will be merged to it.

How to use mail merge to merge the image value

Step 1: Create a new word document and load the document from the file.

Document doc = new Document();
doc.LoadFromFile("Test.docx");

Step 2: Set the value for the mail merge template by the fieldname.

var fieldNames = new string[] { "MyImage" };
var fieldValues = new string[] { "logo.png" };

Step 3: Create a method to get the image file:

void MailMerge_MergeImageField(object sender, MergeImageFieldEventArgs field)
        {
            string filePath = field.FieldValue as string;
            if (!string.IsNullOrEmpty(filePath))
            {
                field.Image = Image.FromFile(filePath);
            }

        }

Step 4: Call the method MailMerge_MergeImageField() to get the image and then merge the specified value into template.

doc.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MailMerge_MergeImageField);

Step 5: Save the document to file.

doc.SaveToFile("result.docx", FileFormat.Docx);

Effective screenshot after merge the image value to the mail merge template:

How to use mail merge to merge the image value

Full codes:

using Spire.Doc;
using Spire.Doc.Reporting;
using System.Drawing;
namespace MailMerge
{
    class Program
    {

        class MailMergeImage
        {
            public MailMergeImage()
            {
                Document doc = new Document();
                doc.LoadFromFile("Test.docx");
                var fieldNames = new string[] { "MyImage" };
                var fieldValues = new string[] { "logo.png" };

                doc.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MailMerge_MergeImageField);

                doc.MailMerge.Execute(fieldNames, fieldValues);

                doc.SaveToFile("result.docx", FileFormat.Docx);
            }

            void MailMerge_MergeImageField(object sender, MergeImageFieldEventArgs field)
            {
                string filePath = field.FieldValue as string;
                if (!string.IsNullOrEmpty(filePath))
                {
                    field.Image = Image.FromFile(filePath);
                }

            }
        }

    }
}
Published in Mail Merge

Mail merge is one of the most important feature offered by Spire.Doc to enable developers to create a report and merge the data. This article will demonstrate how to create a mail merge template and then merge the text value to the template in C# with the help of Spire.Doc.

Here comes to the details of how to create the mail merge and merge the data to it.

Step 1: Create a new word document and add section and paragraph to it.

Document doc = new Document();
Section sec = doc.AddSection();
Paragraph para = sec.AddParagraph();

Step 2: Add two mail merge templates to the paragraph.

para.AppendText("Quantity: ");
para.AppendField("Quantity", FieldType.FieldMergeField);
para.AppendBreak( BreakType.LineBreak);
para.AppendText("Date: ");
para.AppendField("Date", FieldType.FieldMergeField);     

Step 3: Set the value for the mail merge template by the fieldname.

string[] fieldName = {  "Quantity", "Date"};
string[] fieldValue = {  "1800", DateTime.Now .ToShortDateString()};

Step 4: Merge the specified value into template.

doc.MailMerge.Execute(fieldName, fieldValue);

Step 5: Save the document to file.

doc.SaveToFile("result.docx", FileFormat.Docx);

Effective screenshot for the mail merge:

How to create mail merge and merge the text value

Full codes:

using Spire.Doc;
using Spire.Doc.Documents;
using System;
namespace MailMerge
{
    class Program
    {
        static void Main(string[] args)
        {

            Document doc = new Document();
            Section sec = doc.AddSection();
            Paragraph para = sec.AddParagraph();

            para.AppendText("Quantity: ");
            para.AppendField("Quantity", FieldType.FieldMergeField);
            para.AppendBreak(BreakType.LineBreak);
            para.AppendText("Date: ");
            para.AppendField("Date", FieldType.FieldMergeField);

            string[] fieldName = { "Quantity", "Date" };
            string[] fieldValue = { "1800", DateTime.Now.ToShortDateString() };

            doc.MailMerge.Execute(fieldName, fieldValue);

            doc.SaveToFile("result.docx", FileFormat.Docx);

        }

    }
Published in Mail Merge
Tuesday, 26 July 2011 07:05

How to Use Mail Merge in Silverlight

Introduction

Mail merge is often used to print reports in bulk, such as financial statement, payroll or transcript. And the merged documents can be sent by E-mail.

In this article, I will show one way to generate mail merged reports via Spire.Doc.

Steps

We need to finish the following 3 steps to generate our report.

  • Create a mail merge template.
  • Load data from database.
  • Merge data into template and save.

Every step includes several sub-steps and in #2 and #3 we need to write some code.

Create mail merge template

A template is a reusable document. It renders the pattern of our report. We could modify it to change our report without any modification of code.

Note: in this section, all tables mean DataTable instance, not physical table in database.

First, We can create the template in MS Word or by other program. It is the template we need to create. Data will be filled in the red party.

Mail Merge Fax

Second, Insert mail-merge-field as placeholder into the red-block. There are three types of mail-merge-field:

  • GeneralField is a general Word mail-merge-field. It is real data field and our data will be filled in it during merge process.
  • TableField is assistant mail-merge-field and used as a container of multiple related GeneralFields and other TableFields. So it is not data placeholder and no data will be filled in. It is composed of two special mail-merge-fields: TableStart:TableName and TableEnd:TableName. During merge process, the data of related GeneralFields contained by one same TableField will be from one same data table.
  • GroupField is assistant mail-merge-field too. It can contain multiple related GeneralFields and TableFields. It is composed of two special mail-merge-fields: GroupStart:GroupName and GroupEnd:GroupName. During merge process, all Word document elements included in a GroupField will be copied. One row in data table has one copy and data in the row will be filled into the fields in the copy. If the row has sub data table, the data in sub data table will be filled into the fields included in the corresponding TableField. If the sub data table has multiple data rows, the corresponding TableField will be copied and filled too. We need to insert a mail-merge-field named GroupStart:Order in the top of the template body and insert a mail-merge-field named GroupEnd:OrderM in the bottom of the template body.

In this Silverlight application we only use GeneralField. As the image shows below. Insert mail-merge-field as placeholder into the red-block.

Mail Merge Fax

Load Data

Spire.Doc provides merge data from various kind of datasources. This program merge data from a string array which is filled by user.

Mail Merge Fax

using Spire.Doc;
using System;
using System.IO;
namespace MailMerge
{
    class Program
    {
        static void Main(string[] args)
        {
            String[] fieldNames
                = new String[] { "Contact Name", "Fax", "From", "Date", "Subject", "Content" };
            DateTime faxDate
                = this.datePickerFaxDate.SelectedDate.HasValue ?
                    this.datePickerFaxDate.SelectedDate.Value : DateTime.Now;
            String[] fieldValues
                = new String[] 
                {
                    this.textBoxTo.Text,
                    this.textBoxFax.Text,
                    this.textBoxFrom.Text,
                    faxDate.ToShortDateString(),
                    this.textBoxSubject.Text,
                    this.textBoxContent.Text
                };
            this.documentTemplate.MailMerge.Execute(fieldNames, fieldValues);

            bool? result = this.saveFileDialog.ShowDialog();
            if (result.HasValue && result.Value)
            {
                using (Stream stream = this.saveFileDialog.OpenFile())
                {
                    //this.documentTemplate.SaveToStream(stream, FileFormat.Doc);
                    this.documentTemplate.SaveToFile(stream, FileFormat.Doc);
                }


            }
        }
    }
}

Merge data into template and save

In this section, we need to write some code to call Spire.Doc to merge our data and template.

this.documentTemplate.MailMerge.Execute(fieldNames, fieldValues);

            bool? result = this.saveFileDialog.ShowDialog();
            if (result.HasValue && result.Value)
            {
                using (Stream stream = this.saveFileDialog.OpenFile())
                {
                    //this.documentTemplate.SaveToStream(stream, FileFormat.Doc);
                    this.documentTemplate.SaveToFile(stream, FileFormat.Doc);
                }
            }

The Result

Mail Merge Fax

Published in Mail Merge
Wednesday, 13 April 2011 03:21

How to Use Mail Merge to Create Report

Introduction

Mail merge is often used to print reports in bulk, such as financial statement, payroll or transcript. And the merged documents can be sent by E-mail.

In this article, I will show one way to generate mail merged reports via Spire.Doc.

Report Overview

This report includes multiple invoices, and each invoice starts in a new page. Invoice logo and supplier information will present in the header of every page.

Order, shipment, customer, order details and total price make up a completed invoice.

The following pictures show the appearance of invoice:

Mail Merge Report

Content details in each invoice are shown as following:

Mail Merge Report

Order Data Overview

All data in this example is from Northwind database, which is a sample database provided by Microsoft Access 2003.

We will export data from table Orders, Shippers, Customers, Employees, [Order Details] and Products to generate our report. The following picture shows the relationship between the 6 tables.

Mail Merge Report

Steps

We need to finish the following 3 steps to generate our report.

  • Create a mail merge template.
  • Load data from database.
  • Merge data into template and save.

Every step includes several sub-steps and in #2 and #3 we need to write some code.

Create mail merge template

A template is a reusable document. It renders the pattern of our report. We could modify it to change our report without any modification of code.

Note: in this section, all tables mean DataTable instance, not physical table in database.

We can create the template in MS Word or by other program. Please see the following picture. It is the template we need to create. Data will be filled in the red party.

Mail Merge Report

Insert mail-merge-field as placeholder into the red-block. There are three types of mail-merge-field which will be used in this example:

GeneralField is a general Word mail-merge-field. It is real data field and our data will be filled in it during merge process. We need to insert a GeneralField to every red-block and name these fields with the corresponding data name. After inserting GeneralFields, our template will looks like:

Mail Merge Report

TableField is assistant mail-merge-field and used as a container of multiple related GeneralFields and other TableFields. So it is not data placeholder and no data will be filled in. It is composed of two special mail-merge-fields:

TableStart:TableName and TableEnd:TableName. During merge process, the data of related GeneralFields contained by one same TableField will be from one same data table. For example, fields in Customer information block will be filled with data from data table Customer, so we need to put them in TableField Customer.

Insert a mail-merge-field with field name TableStart:Customer immediately before the first CompanyName field and insert another mail-merge-field with field name TableEnd:Customer immediately after the field Country. And then our fields in Customer information block looks like:

Mail Merge Report

During the merge process, data in column CompanyName of table Customer will be filled in the field CompanyName, Customer.Address to field Address, Customer.City to field City and so on.

Data of fields in column Salesperson in Order information table is from table Employee

Mail Merge Report

Data of fields in column Ship Via in Order information table is from table Shipper

Mail Merge Report

Data of fields in Order details table is from table Detail, except field ProductName. Data of field ProductName is from table Product. Data of field InvoiceSubtotal and InvoiceTotal in Invoice total information is from table Total (virtual table)

Mail Merge Report

GroupField is assistant mail-merge-field too. It can contain multiple related GeneralFields and TableFields. It is composed of two special mail-merge-fields: GroupStart:GroupName and GroupEnd:GroupName. During merge process, all Word document elements included in a GroupField will be copied. One row in data table has one copy and data in the row will be filled into the fields in the copy.

If the row has sub data table, the data in sub data table will be filled into the fields included in the corresponding TableField. If the sub data table has multiple data rows, the corresponding TableField will be copied and filled too.

We need to insert a mail-merge-field named GroupStart:Order in the top of the template body and insert a mail-merge-field named GroupEnd:Order in the bottom of the template body. After this, our template looks like:

Mail Merge Report

You could find the complete template named InvoiceTemplate.doc in the attached source package.

Load Data from Database

Spire.Doc provides merge data from DataSet. So we will use DataAdapter to fill data table from NorthWind database to a DataSet and merge it into our template. Difference from DataRelation of DataSet, Spire.Doc has owned table relation functionality. So we don't need to create DataRelation instance for the DataSet object. The code below just shows load Order data. Please see the attached source package for other code.

[C#]
String connectionString
    = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Northwind.mdb";
DataSet dataSet = new DataSet();
using(OleDbConnection conn = new OleDbConnection(connectionString))
{
    //load December 1997 orders
    String sql
        = " SELECT * "
        + " FROM   Orders "
        + " WHERE  ShippedDate Between #12/1/1997# And #12/31/1997# ";
    using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, conn))
    {
        dataAdapter.Fill(dataSet, "Order");
    }
}

Merge data into template and save

In this section, we need to write some code to call Spire.Doc to merge our data table and template.

Create Spire.Doc.Document object and load template.

[C#]
Document document = new Document();
document.LoadFromFile("InvoiceTemplate.doc", FileFormat.Doc);

Establish relationship between data tables.

[C#]
List<DictionaryEntry> list = new List<DictionaryEntry>
{
    new DictionaryEntry("Order", String.Empty),
    new DictionaryEntry("Shipper", "ShipperID = %Order.ShipVia%"),
    new DictionaryEntry("Customer", "CustomerID = %Order.CustomerID%"),
    new DictionaryEntry("Employee", "EmployeeID = %Order.EmployeeID%"),
    new DictionaryEntry("Detail", "OrderID = %Order.OrderID%"),
    new DictionaryEntry("Product", "ProductID = %Detail.ProductID%"),
    new DictionaryEntry("Total", "OrderID = %Order.OrderID%")
};

Merge data set into template and save document to file.

[C#]
//clear empty value fields during merge process
document.MailMerge.ClearFields = true;

//clear empty paragraphs if it has only empty value fields.
document.MailMerge.RemoveEmptyParagraphs = true;

//merge
document.MailMerge.ExecuteWidthNestedRegion(dataSet, list);

//set word view type.
document.ViewSetup.DocumentViewType = DocumentViewType.PrintLayout;
document.SaveToFile("Invoice.doc");

In order to start each invoice in a new page, we insert a page-break-symbol immediately before the first paragraph when a new order row will be merged. To do this, we need to handle the event MergeField which is fired before a field merged.

[C#]
//index of row of merged order data
int mergedRowIndex = 0;
document.MailMerge.MergeField += delegate(object sender, MergeFieldEventArgs e)
{
    if (e.TableName == "Order")
    {
        if (e.RowIndex > mergedRowIndex)
        {
            mergedRowIndex = e.RowIndex;
            
            //insert page break symbol before the paragraph of current field
            InsertPageBreak(e.CurrentMergeField);
        }
    }
};

Code of method InsertPageBreak

[C#]
private static void InsertPageBreak(IMergeField field)
{
    //append a page break symbol
    Break pageBreak = field.OwnerParagraph.AppendBreak(BreakType.PageBreak);

    //move to the start of the paragraph
    field.OwnerParagraph.Items.Insert(0, pageBreak);
}
Published in Mail Merge