Создание отчетов и Mail Merge: Создайте простой отчет с использованием C# и .Net


This C# App shows how to create 5 populated by data Docx documents from a Word template (*.docx).

Introduction

Mail Merge is the feature which allows to easy generate documents populated by data using a template.

To illustrate how works Mail Merge function, let's create C# application which generates envelopes "Happy New Year" for Simpson family. As result we'll get five personal Happy New Year greetings in a single document.

This C# App shows how to create 5 populated by data Docx documents from a Word template (*.docx)
Five personal greetings in the single document.

Two main steps:

  1. Create template «envelope-template.docx» in MS Word with Fields "Name" and "FamilyName".
  2. Create C# Console app which executes Mail Merge between Simpson's data and template and generates «simpson-family.docx»

1. Create an envelope template in MS Word: envelope-template.docx

To start, open MS Word and create a new document with the name "envelope-template.docx". Next add some images and a text to congratulate the Simpson's family. Next, is our main goal - add two Fields: "Name" and "FamilyName".
If you are already familiar with adding of Merge Fields, you may skip this step and use completely ready «envelope-template.docx»

How to Insert a Merge Field

  1. Select "INSERT" tab.
  2. Click by the pictogram "Quick Parts".
  3. Select and click by "Field.." menu item.
  4. In the opened window, follow to the "Field names:" and select "MergeField".
  5. In the "Field name:" type Name.
  6. Click "OK".
How to create a template with Merge Fields in MS Word

Here you may an extra information how to Insert Merge Fields

As result of the Step 1 we've to get: envelope-template.docx

2. Create C# Console app which executes Mail Merge

  1. Launch Visual Studio and Create a new Console App C# (.Net Framework or .Net Core) with name "Simpsons".
  2. You may add the reference to the SautinSoft.Document assembly by two ways:

    1. Nuget (fast way):

    (Solution Explorer->right click by "References"->Manage Nuget Packages...->In the tab "Browse" type "SautinSoft" and find the "SautinSoft.Document")
    Add SautinSoft.Document.dll via Nuget.

    2. Old good way by adding the reference:

    First of all, download the SautinSoft.Document package (document_net.zip) from the SautinSoft website.
    Unzip document_net.zip and find the assembly file "SautinSoft.Document.dll".
    (At the Solution Explorer->right click by "References"->Add Reference...->Browse "SautinSoft.Document.dll")
    Add reference to SautinSoft.Document.dll.

    Note:

    SautinSoft.Document.dll compiled for .NET Core is located inside (document_net.zip->SautinSoft.Document X.X\Bin\.NET Core X.X) folder.

    SautinSoft.Document.dll compiled for .NET Framework is located inside (document_net.zip->SautinSoft.Document X.X\Bin\.NET Framework X.X) folder.

  3. Type the code of our App: (We've also prepared the code for VB.Net developers)

Полный код

using System;
using System.IO;
using SautinSoft.Document;

namespace Sample
{
    class Sample
    {
        static void Main(string[] args)
        {
            MailMergeSimpleEnvelope();
        }

        /// <summary>
        /// Generates 5 envelopes "Happy New Year" for Simpson family using the one template.
        /// </summary>
        /// <remarks>
        /// See details at: https://sautinsoft.com/products/document/help/net/developer-guide/mail-merge-simple-report-net-csharp-vb.php
        /// </remarks>
        public static void MailMergeSimpleEnvelope()
        {
            string templatePath = @"..\..\..\envelope-template.docx";
            string resultPath = "Simpson-family.docx";

            DocumentCore dc = DocumentCore.Load(templatePath);

            var dataSource = new[] { new { Name = "Homer", FamilyName = "Simpson" },
                                new { Name = "Marge ", FamilyName = "Simpson" },
                                new { Name = "Bart", FamilyName = "Simpson" },
                                new { Name = "Lisa", FamilyName = "Simpson" },
                                new { Name = "Maggie", FamilyName = "Simpson" }};

            dc.MailMerge.Execute(dataSource);
            dc.Save(resultPath);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(resultPath) { UseShellExecute = true });
        }
    }
}

Скачать

Option Infer On

Imports System
Imports System.IO
Imports SautinSoft.Document
Module Sample
    Sub Main()
        MailMergeSimpleEnvelope()
    End Sub

    ''' <summary>
    ''' Generates 5 envelopes "Happy New Year" for Simpson family using the one template.
    ''' </summary>
    ''' <remarks>
    ''' See details at: https://sautinsoft.com/products/document/help/net/developer-guide/mail-merge-simple-report-net-csharp-vb.php
    ''' </remarks>
    Sub MailMergeSimpleEnvelope()
        Dim templatePath As String = "..\..\..\envelope-template.docx"
        Dim resultPath As String = "Simpson-family.docx"

        Dim dc As DocumentCore = DocumentCore.Load(templatePath)

        Dim dataSource = {
            New With {
                Key .Name = "Homer",
                Key .FamilyName = "Simpson"
            },
            New With {
                Key .Name = "Marge ",
                Key .FamilyName = "Simpson"
            },
            New With {
                Key .Name = "Bart",
                Key .FamilyName = "Simpson"
            },
            New With {
                Key .Name = "Lisa",
                Key .FamilyName = "Simpson"
            },
            New With {
                Key .Name = "Maggie",
                Key .FamilyName = "Simpson"
            }
        }

        dc.MailMerge.Execute(dataSource)
        dc.Save(resultPath)

        ' Open the result for demonstration purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(resultPath) With {.UseShellExecute = True})
    End Sub

End Module

Скачать


After execution of mail merge method we'll get the «simpson-family.docx» as result.

How to create a template with Merge Fields in MS Word

Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.