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


В этом расширенном примере показано, как сгенерировать табличный отчет с регионами, используя шаблон почтового слияния и XML-документ в качестве источника данных.

Здесь мы будем формировать счета-фактуры для кондитерской. Для создания счетов-фактур нам понадобится только шаблон DOCX и XML-документ, заполненный заказами и кондитерскими изделиями.
Кроме того, мы покажем вам, как с помощью FieldMerging событие вставьте фотографии и отформатируйте валюту подпишите внутри определенных полей и диапазонов.

1. Создайте шаблон в MS Word с Merge Fields или используйте готовый файл «InvoiceTemplate.docx».

Записка. Если лист заказа должен начинаться с новой страницы, выполните следующие действия.

2. Затем мы создаем XML-документ, заполненный данными. Как вы можете видеть, имена тегов имеют одинаковые названия как поля слияния.
Это наш XML-документ: «Orders.xml»

Кстати, вы можете создать аналогичный XML-документ в своем приложении, используя Serialization. Ниже вы увидите демонстрационное WPF-приложение, в котором мы также использовали Serialization.

3. После выполнения метода слияния мы получим «Invoices.pdf» как результат. Полный код на C# и VB.Net находится внизу этой страницы.

Интересный: Чтобы убедиться в этой функциональности, мы создали для вас полный WPF C# demo-app в котором показан полный процесс создания накладных в реальной кондитерской.

С помощью этого приложения вы можете создать новый XML-документ, заполненный заказами на торты, пирожные, хлебобулочные изделия и плюшки, а также сгенерировать счет-фактуру в форматах PDF, DOCX, RTF и HTML. Скачать WPF - Pastry Shop, исходные тексты на C#(115 Kb).

Полный код

using System;
using System.Data;
using System.IO;
using System.Collections.Generic;

using SautinSoft.Document;
using SautinSoft.Document.Drawing;
using System.Globalization;

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

        /// <summary>
        /// Generates a table report with regions using XML document as a data source and FieldMerging event.
        /// </summary>
        /// <remarks>
        /// See details at: https://www.sautinsoft.com/products/document/help/net/developer-guide/mail-merge-table-report-with-regions-advanced-net-csharp-vb.php
        /// </remarks>
        public static void TableReportWithRegionsAdvanced()
        {
            // Scan directory for image files.
            Dictionary<string, string> icons = new Dictionary<string, string>();
            foreach (string iconPath in Directory.EnumerateFiles(@"..\..\icons\", @"*.jpg"))
            {
                icons[Path.GetFileNameWithoutExtension(iconPath.ToLower())] = iconPath;

                switch (Path.GetFileName(iconPath))
                {
                    case "Cherry-apple pie.jpg": icons["Cherry/apple/pie".ToLower()] = iconPath; break;
                    case "Dark-milk-white chocolate.jpg": icons["Dark/milk/white chocolate".ToLower()] = iconPath; break;
                    case "Rice-lemon-vanilla pudding.jpg": icons["Rice/lemon/vanilla pudding".ToLower()] = iconPath; break;
                    case "Spice-cake honey-cake.jpg": icons["Spice-cake, honey-cake".ToLower()] = iconPath; break;
                    case "Chocolate-strawberry-vanilla ice cream.jpg": icons["Chocolate/strawberry/vanilla ice cream".ToLower()] = iconPath; break;
                    default:break;
                }
            }

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

            // Each product will be decorated by appropriate icon.
            dc.MailMerge.FieldMerging += (sender, e) =>
            {
                // Insert an icon before the product name
                if (e.RangeName == "Product" && e.FieldName == "Name")
                {
                    e.Inlines.Clear();

                    string iconPath;
                    if (icons.TryGetValue(((string)e.Value).ToLower(), out iconPath))
                    {
                        e.Inlines.Add(new Picture(dc, iconPath) { Layout = new InlineLayout(new Size(30, 30)) });                        
                        e.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.Tab));
                    }

                    e.Inlines.Add(new Run(dc, (string)e.Value));
                    e.Cancel = false;
                }
                // Add the currency sign into "Total" field. 
                // You may change the culture "en-GB" to any desired.
                if (e.RangeName == "Order" && e.FieldName == "OrderTotal")
                {
                    decimal total = 0;
                    if (Decimal.TryParse((string)e.Value, out total))
                    {
                        e.Inlines.Clear();                        
                        e.Inlines.Add(new Run(dc, String.Format(new CultureInfo("en-GB"), "{0:C}", total)));
                    }                    
                }
            };

            // 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 System.Collections.Generic

Imports SautinSoft.Document
Imports SautinSoft.Document.Drawing
Imports System.Globalization

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

        ''' <summary>
        ''' Generates a table report with regions using XML document as a data source and FieldMerging event.
        ''' </summary>
        ''' <remarks>
        ''' See details at: https://www.sautinsoft.com/products/document/help/net/developer-guide/mail-merge-table-report-with-regions-advanced-net-csharp-vb.php
        ''' </remarks>
        Public Shared Sub TableReportWithRegionsAdvanced()
			' Scan directory for image files.
			Dim icons As New Dictionary(Of String, String)()
            For Each iconPath As String In Directory.EnumerateFiles("..\icons\", "*.jpg")
                icons(Path.GetFileNameWithoutExtension(iconPath.ToLower())) = iconPath

                Select Case Path.GetFileName(iconPath)
                    Case "Cherry-apple pie.jpg"
                        icons("Cherry/apple/pie".ToLower()) = iconPath
                    Case "Dark-milk-white chocolate.jpg"
                        icons("Dark/milk/white chocolate".ToLower()) = iconPath
                    Case "Rice-lemon-vanilla pudding.jpg"
                        icons("Rice/lemon/vanilla pudding".ToLower()) = iconPath
                    Case "Spice-cake honey-cake.jpg"
                        icons("Spice-cake, honey-cake".ToLower()) = iconPath
                    Case "Chocolate-strawberry-vanilla ice cream.jpg"
                        icons("Chocolate/strawberry/vanilla ice cream".ToLower()) = iconPath
                    Case Else
                End Select
            Next iconPath

            ' 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)

			' Each product will be decorated by appropriate icon.
			AddHandler dc.MailMerge.FieldMerging, Sub(sender, e)
				' Insert an icon before the product name
				If e.RangeName = "Product" AndAlso e.FieldName = "Name" Then
					e.Inlines.Clear()

					Dim iconPath As String = Nothing
					If icons.TryGetValue(CStr(e.Value).ToLower(), iconPath) Then
						e.Inlines.Add(New Picture(dc, iconPath) With {.Layout = New InlineLayout(New Size(30, 30))})
						e.Inlines.Add(New SpecialCharacter(dc, SpecialCharacterType.Tab))
					End If

					e.Inlines.Add(New Run(dc, CStr(e.Value)))
					e.Cancel = False
				End If
				' Add the currency sign into "Total" field.
				' You may change the culture "en-GB" to any desired.
				If e.RangeName = "Order" AndAlso e.FieldName = "OrderTotal" Then
					Dim total As Decimal = 0
					If Decimal.TryParse(CStr(e.Value), total) Then
						e.Inlines.Clear()
						e.Inlines.Add(New Run(dc, String.Format(New CultureInfo("en-GB"), "{0:C}", total)))
					End If
				End If
			End Sub

			' 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. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.