Mail Merge: Табличный отчет с регионами на C# и VB .Net


This example shows how to generate Table Report with regions using a mail merge template and XML-document as a data source.

Here we'll generate invoices for a pastry shop. To generate invoices, all what we need are DOCX-template and XML-document populated by orders and pastry items.

1. Create a template in MS Word with Merge Fields or use a ready file «InvoiceTemplate.docx».

Note. If the order sheet should start from a new page, do the following.

2. Then we create XML-document populated by data. As you may see that tag names have the same names as the merge fields.
This our XML-document: «Orders.xml»

By the way, you may create similar XML-document in your app using a Serialization. Below you will see the demo WPF-app where we have used Serialization too.

3. After execution of mail merge method we'll get the «Invoices.pdf» as result. The complete code in C# and VB.Net is located at the bottom ot this page.

Interesting: To see this functionality firsthand, we've created for you complete WPF C# demo-app which shows the full process of creating invoices in a real Pastry Shop.

With help of this application you can create new XML-document populated by orders with pies, cakes, bread and buns and generate an invoice in PDF, DOCX, RTF and HTML formats. Download WPF - Pastry Shop, C# sources(115 Kb).

Полный код

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

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

        /// <summary>
        /// Generates a table report with regions using XML document as a data source.
        /// </summary>
        /// <remarks>
        /// See details at: https://www.sautinsoft.com/products/document/help/net/developer-guide/mail-merge-table-report-with-regions-net-csharp-vb.php
        /// </remarks>
        public static void TableReportWithRegions()
        {
            // Create the Dataset and read the XML.
            DataSet ds = new DataSet();

            ds.ReadXml(@"..\..\..\Orders.xml");

            // Load the template document.
            string templatePath = @"..\..\..\InvoiceTemplate.docx";

            DocumentCore dc = DocumentCore.Load(templatePath);

            // Execute the mail merge.
            dc.MailMerge.Execute(ds.Tables["Order"]);

            string resultPath = "Invoices.pdf";

            // Save the output to file
            dc.Save(resultPath);

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

Скачать

Imports System
Imports System.Data
Imports System.IO
Imports SautinSoft.Document

Namespace Sample
    Friend Class Sample
        Shared Sub Main(ByVal args() As String)
            TableReportWithRegions()
        End Sub

        ''' <summary>
        ''' Generates a table report with regions using XML document as a data source.
        ''' </summary>
        ''' <remarks>
        ''' See details at: https://www.sautinsoft.com/products/document/help/net/developer-guide/mail-merge-table-report-with-regions-net-csharp-vb.php
        ''' </remarks>
        Public Shared Sub TableReportWithRegions()
            ' Create the Dataset and read the XML.
            Dim ds As New DataSet()

            ds.ReadXml("..\..\..\Orders.xml")

            ' Load the template document.
            Dim templatePath As String = "..\..\..\InvoiceTemplate.docx"

            Dim dc As DocumentCore = DocumentCore.Load(templatePath)

            ' Execute the mail merge.
            dc.MailMerge.Execute(ds.Tables("Order"))

            Dim resultPath As String = "Invoices.pdf"

            ' Save the output to file
            dc.Save(resultPath)

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

Скачать


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



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

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