翻譯|使用教程|編輯:胡濤|2022-04-22 13:14:54.350|閱讀 222 次
概述:本文將介紹在 C# 中為組創建郵件合并,歡迎下載體驗!
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
在 Spire.Doc 中,我們可以使用郵件合并將數據源中的多條記錄插入到 Word 模板文檔中的指定區域。該區域必須由兩個具有特殊名稱的合并文件標記,如?GroupStart:GroupName?和?GroupEnd:GroupName?,其中GroupStart和GroupEnd表示一個組的起點和終點,它也是該區域的起點和終點。執行郵件合并后,該區域會針對數據源中的每條記錄重復。
為了更好地演示,我們創建了一個包含合并字段的模板文檔,如下所示:
在這個模板中,“產品”是組名,我們在使用代碼執行郵件合并時應該使用相同的名稱。合并文件“GroupStart:Products”和“GroupEnd:Products”表示組和區域的開始和結束。
代碼片段:
一開始,我們定義了一個名為“Product”的類,在其中我們創建了一個構造函數Product(int number,string type,string name,string price,string vendor,string expirydate)并添加了四個屬性“ Number ”,“ Type ”, “名稱”、“價格”、“供應商”和“到期日期”。
第 1 步:實例化 Product 類的兩個對象并將它們添加到列表中。
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);
第 2 步:加載模板文檔。
Document document = new Document("ProductsList.docx");
第 3 步:使用列表作為數據源并為“產品”組執行郵件合并。
MailMergeDataTable table = new MailMergeDataTable("Products", list); document.MailMerge.ExecuteGroup(table);
第 4 步:保存文檔。
document.SaveToFile("Output.docx");
執行上述代碼后,我們會得到如下結果文件:
完整代碼:
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; } } }
歡迎下載|體驗更多E-iceblue產品
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn