對于Word中的郵件合并功能,使用者可以将郵件合并後的結果文檔儲存并列印,也可以通過郵件的形式發送,在很多場合需要使用到此功能。那對于程式設計人員,我們也可以在C#語言環境中通過代碼的形式來實作。根據需要先建立郵件合并模闆後,可合并文本和圖檔,在下面的方法中,需要使用到元件Free Spire.Doc for .NET 。建立模闆前,需先安裝該元件,注意添加引用該元件dll檔案到控制台應用程式中,同時添加命名空間。
一、建立郵件合并模闆
第一步:添加命名空間
using System;
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
using Spire.Doc.Fields;
第二步:主要代碼段
//建立一個Document類對象,并添加Section
Document document = new Document();
Section section = document.AddSection();
//添加段落到Section,并向段落添加文字,設定文字顔色、字型粗細
Paragraph paragraph = section.AddParagraph();
TextRange tr = paragraph.AppendText("人 物 基 本 信 息");
tr.CharacterFormat.TextColor = Color.YellowGreen;
tr.CharacterFormat.Bold = true;
//添加文本,并添加合并域“Image:Portrait”
paragraph.AppendText("\n人 物 肖 像 : ");
paragraph.AppendField("Image:Portrait", FieldType.FieldMergeField);
//添加文本,并添加合并域“Name”
paragraph.AppendText("\n姓 名 : ");
paragraph.AppendField("Name", FieldType.FieldMergeField);
//添加文本,并添加合并域“Nation”
paragraph.AppendText("\n民 族 :");
paragraph.AppendField("Nation", FieldType.FieldMergeField);
//添加文本,并添加合并域“Nationality”
paragraph.AppendText("\n國 籍 : ");
paragraph.AppendField("Nationality", FieldType.FieldMergeField);
//添加文本,并添加合并域“Graduated From”
paragraph.AppendText("\n院 校 : ");
paragraph.AppendField("Graduated From", FieldType.FieldMergeField);
//儲存并打開文檔
document.SaveToFile("模闆.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("模闆.docx");
完成以上步驟後,調試運作程式,生成檔案(可在項目檔案下bin>Debug中檢視)
如下圖:

二:合并文本、圖檔
在完成模闆建立之後,可添加文本和圖檔,如下:
using System;
using Spire.Doc;
using System.Drawing;
using Spire.Doc.Reporting;
第二步:主要代碼段
static void Main(string[] args)
{
//執行個體化一個Document類,并加載文檔模闆
Document doc = new Document();
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\模闆.docx");
var textFieldNames = new string[] { "Name", "Nation", "Nationality", "Graduated From"};
var textFieldValues = new string[] { "喬 治•華 盛 頓 (George Washington)", "美 利 堅 民 族", "美 國", "威 廉 與 瑪 麗 學 院 (William and Mary)"};
var imageFieldNames = new string[] { "Portrait" };
var imageFieldValues = new string[] { @"C:\Users\Administrator\Desktop\images\華盛頓.jpg" };
//合并文本到模闆
doc.MailMerge.Execute(textFieldNames, textFieldValues);
//建立合并圖檔自定義事件
doc.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MailMerge_MergeImageField);
//合并圖檔到模闆
doc.MailMerge.Execute(imageFieldNames, imageFieldValues);
//儲存并打開文檔
doc.SaveToFile("result.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("result.docx");
}
//添加自定義事件載入圖檔
static void MailMerge_MergeImageField(object sender, MergeImageFieldEventArgs field)
{
string filePath = field.FieldValue as string;
if (!string.IsNullOrEmpty(filePath))
{
field.Image = Image.FromFile(filePath);
}
}
運作程式,生成檔案,如下圖:
以上全部内容為本文建立郵件合并模闆并合并文本和圖檔的方法講述,方法中使用到的元件Spire.Doc for .NET在處理Word文檔方面具有很好的輔助作用,感興趣的話可以動手試試。如果本文對你有所幫助,歡迎轉載(轉載請注明出處)。