How to create mail merge and merge the text value

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:

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);
}