郵件合併是 Microsoft Word 的功能,可用於快速輕鬆地建立信件、標籤和信封等文件。 Aspose.Words Cloud 採用標準郵件合併並將其向前推進了許多步驟,將其轉變為成熟的報告解決方案,使您可以生成更複雜的文檔,例如報告、目錄、庫存和發票。 Aspose.Words Cloud 報告解決方案的優點是:

  • 使用標準郵件合併欄位在 Microsoft Word 中設計報告
  • 定義文件中增長的區域,例如訂單的詳細資訊行
  • 在郵件合併期間插入影像
  • 在郵件合併期間插入 HTML

基本步驟

執行郵件合併的步驟非常簡單。首先,使用 Microsoft Word 建立和設計 Word 文檔,通常稱為範本。請注意,該文件不必是 Microsoft Word 範本 (.dot),它可以是普通的 .doc 文件。您可以將一些稱為合併欄位的特殊欄位插入到範本中您希望稍後插入資料來源中的資料的位置。然後使用 Aspose.Words REST API,執行郵件合併操作。郵件合併作業將從您的資料來源取得資料並將其合併到文件中。

您也可以在文件中指定可重複的合併區域或插入特殊的合併字段,以允許您插入其他內容(例如影像)。根據您在文件中設定郵件合併欄位和可重複區域的方式,文件將增長以容納資料來源中的多個記錄。如果不使用郵件合併區域,則郵件合併將類似於 Microsoft Word 郵件合併,並且將為資料來源中的每筆記錄重複整個文件內容。使用可重複的郵件合併區域,您可以指定文件中將針對資料來源中的每筆記錄重複的部分。例如,如果將表行標記為可重複區域,則該表行將重複,導致表動態增長以容納所有資料。

準備文件

在執行郵件合併之前,您需要準備文件範本。您應該插入將被資料來源中的值取代的合併欄位。

將合併欄位插入文檔

若要將合併欄位插入文件中:

  1. 在 Microsoft Word 中開啟您的文件。
  2. 在文件中,按一下要放置合併欄位的位置。
  3. 打開“插入”選單並選擇“字段”以開啟“字段”對話框。
  4. 從欄位名稱清單中,選擇合併欄位。
  5. 在欄位名稱文字方塊中,輸入合併欄位的名稱,然後按確定。

由於合併字段是常規 Microsoft Word 字段,因此您可以使用鍵盤快捷鍵 Alt+F9 在 Microsoft Word 文件中的顯示字段代碼和結果之間切換。字段代碼出現在花括號之間。

簡單的郵件合併

為了準備範本來執行簡單的郵件合併(沒有區域,類似於 Microsoft Word 中可用的經典郵件合併),您應該只在要使用資料來源中的資料填入的位置插入一個或多個合併欄位。

讓我們看一下晚宴邀請演示。它為資料來源中定義的客戶端清單建立一封信。此範本包含許多由兩個資料來源填入的合併欄位;換句話說,兩個郵件合併是一個接一個地執行的。首先,將來自第一個資料來源的資料合併到範本中。此資料來源僅包含一行,因為這是有關邀請者的信息,因此整個文件內容不會重複,僅填入相應的欄位資料。然後執行第二次郵件合併操作。它使用的資料來源包含有關客戶端的資訊。每個資料行都會重複整個模板,並且每個重複的副本都會填入對應客戶端的資料。

郵件合併

結果,我們得到了一份由五封填寫完整的個人化邀請函組成的文件(第一封邀請函的片段如下所示):

執行郵件合併

正如您所看到的,使用相同範本執行多個合併操作以分階段添加資料是可能的,有時甚至是有用的。您可以在Word文件中插入NEXT字段,以使郵件合併引擎從資料來源中選擇下一筆記錄並繼續合併。當引擎遇到NEXT欄位時,它只是選擇資料來源中的下一筆記錄並繼續合併,而不複製任何內容。這可以在建立郵件標籤等文件時使用。

執行簡單郵件合併的程式碼如下:

// 完整的範例和資料文件,請造訪 https://github.com/aspose-words-cloud/aspose-words-cloud-dotnet

string MyAppKey = ""; // Get AppKey and AppSID from https://dashboard.aspose.cloud/
string MyAppSid = ""; // Get AppKey and AppSID from https://dashboard.aspose.cloud/

WordsApi wordsApi = new WordsApi(MyAppKey, MyAppSid);
StorageApi storageApi = new StorageApi(MyAppKey, MyAppSid);

var fileName = "DinnerInvitation.docx";
var destFileName = "InviterAdded.docx";
var data = File.ReadAllText(@"c:\Data\" + "Inviter.xml");
string folder = null; // File exists at the root of the storage

// 將來源文檔上傳至雲端存儲
PutCreateRequest request = new PutCreateRequest(fileName, File.OpenRead(@"c:\Data\" + fileName), null, null);
storageApi.PutCreate(request);

// 第一次執行郵件合併操作
var executeMailMergeRequest = new PostDocumentExecuteMailMergeRequest(fileName, data, folder, destFileName: destFileName, withRegions: false);
var actual = wordsApi.PostDocumentExecuteMailMerge(executeMailMergeRequest);

// 第二次執行郵件合併作業
fileName = destFileName;
destFileName = "FinalDinnerInvitation.docx";
data = File.ReadAllText(@"c:\Data\" + "Clients.xml");

executeMailMergeRequest = new PostDocumentExecuteMailMergeRequest(fileName, data, folder, destFileName: destFileName, withRegions: false);
actual = wordsApi.PostDocumentExecuteMailMerge(executeMailMergeRequest);

與區域的郵件合併

如果您想要動態增加文件內的部分,請使用郵件合併區域。若要在文件中指定郵件合併區域,您需要插入兩個郵件合併欄位來標記郵件合併區域的開始和結束。郵件合併區域中包含的所有文件內容將針對資料來源中的每筆記錄自動重複。

若要標記郵件合併區域的開始,請插入名為 TableStart:MyTable 的 MERGEFIELD,其中 MyTable 分別對應於 XML 或 JSON 中的標記或按鍵。若要標記郵件合併區域的結尾,請插入另一個名為 TableEnd:MyTable 的 MERGEFIELD。在這些標記欄位之間,放置與資料來源欄位相對應的合併欄位。這些合併欄位將填入資料來源第一行的數據,然後重複整個區域,新欄位將填入第二行的數據,依此類推。

標記區域時請遵循以下簡單規則:

  • TableStart 和 TableEnd 欄位必須位於文件中的相同部分內
  • 如果在表內使用,TableStart 和 TableEnd 必須位於表中的同一行內
  • 郵件合併區域可以相互嵌套
  • 郵件合併區域應該格式良好(總是有一對具有相同表名的匹配 TableStart 和 TableEnd)

作為範例,請查看專案目錄示範。以下是為郵件合併準備的區域的片段:

郵件合併

請注意,標記欄位 TableStart:Item 和 TableEnd:Item 均放置在 Word 表格的相同行內。執行郵件合併後,結果如下:

簡單的郵件合併

執行區域郵件合併的程式碼如下:

// 如需完整範例和資料文件,請造訪 https://github.com/aspose-words-cloud/aspose-words-cloud-dotnet

string MyAppKey = ""; // Get AppKey and AppSID from https://dashboard.aspose.cloud/
string MyAppSid = ""; // Get AppKey and AppSID from https://dashboard.aspose.cloud/

WordsApi wordsApi = new WordsApi(MyAppKey, MyAppSid);
StorageApi storageApi = new StorageApi(MyAppKey, MyAppSid);

var fileName = "Invoice_Template.doc";
var destFileName = "Invoice_Template_out_.doc";
var data = File.ReadAllText(@"c:\Data\" + "CustomerData.xml");
string folder = null; // File exists at the root of the storage

// 將輸入文檔上傳到雲端存儲
PutCreateRequest request = new PutCreateRequest(fileName, File.OpenRead(@"c:\Data\" + fileName), null, null);
storageApi.PutCreate(request);

var executeMailMergeRequest = new PostDocumentExecuteMailMergeRequest(fileName, data, folder, destFileName: destFileName, withRegions: true);
var actual = wordsApi.PostDocumentExecuteMailMerge(executeMailMergeRequest);

使用“Mustache”範本語法進行郵件合併

此語法允許您建立用於郵件合併的模板,該模板使用純文字標記而不是合併欄位。這些標記如下所示:{{ FieldName }}

物件.屬性語法

您可以使用以下語法輕鬆合併欄位的屬性:

  {{ Address.Street }}  

這將合併 XML 資料中的數據,如下所示:

<Order> // <-- Current context is here.  
  <Number>23</Number>  
  <Address>  
    <Street>Nelson Street</Street>  
    <Suburb>Howick</Suburb>  
    <City>Auckland</City>  
  </Address>  
  <PhoneNumber>543 1234</PhoneNumber>  
</Order>  

Foreach 區塊

您可以使用 foreach 標籤合併來自多個記錄的資料。這類似於具有傳統合併欄位的郵件合併區域。您可以嵌套這樣的區塊。

{{ #foreach Order }}  
  {{ Number }}  
    {{ Address.Street }}  
      {{ #foreach Item }}  
        {{ Description }} {{ Cost}} {{ Total }}  
      {{/foreach Item }}  
{{ /foreach Order }} 

您也可以混合這些欄位並將它們放置在其他 Microsoft Word 欄位中,例如 IF 或公式欄位。

條件區塊

您可以使用 Aspose.Words Cloud 將郵件合併與 IF 語句結合使用。僅當與其關聯的布林表達式為 true 時,IF 區塊才會執行。 IF 的語法如下圖所示。

{ IF "{{ GENDER }}" = “MALE” “true text” “false text” }

使用「Mustache」範本執行郵件合併的程式碼如下:

// 如需完整範例和資料文件,請造訪 https://github.com/aspose-words-cloud/aspose-words-cloud-dotnet

string MyAppKey = ""; // Get AppKey and AppSID from https://dashboard.aspose.cloud/
string MyAppSid = ""; // Get AppKey and AppSID from https://dashboard.aspose.cloud/

WordsApi wordsApi = new WordsApi(MyAppKey, MyAppSid);
StorageApi storageApi = new StorageApi(MyAppKey, MyAppSid);

var fileName = "VendorTemplate.doc";
var destFileName = "VendorTemplate_Out.docx";
string folder = null; // File exists at the root of the storage

var data = File.ReadAllText(@"c:\Data\" + "Vendors.xml");

// 將輸入文檔上傳到雲端存儲
PutCreateRequest request = new PutCreateRequest(fileName, File.OpenRead(@"c:\Data\" + fileName), null, null);
storageApi.PutCreate(request);

var postExecuteTemplateRequest = new PostExecuteTemplateRequest(fileName, data, folder, destFileName: destFileName);
var actual = wordsApi.PostExecuteTemplate(postExecuteTemplateRequest);

在郵件合併期間插入 HTML

executeMailMergeexecuteTemplate API 都支援在合併欄位上插入 HTML。您只需要確保轉義資料來源字串中的 HTML 字元並使用“format”=“html”屬性,如下所示:

{     
  "dataSourceList": {   
    "contractDS": {  
      "contractDescription": {  
        "format":"html",   
        "htmlText": "<b>Test me 1<br><br><i>Test me 2<br><br><u>Test me 2</u></i></b><br>"         
      }       
    }     
  }   
}

以下程式碼顯示如何在郵件合併期間插入 HTML:

// 如需完整範例和資料文件,請造訪 https://github.com/aspose-words-cloud/aspose-words-cloud-dotnet

using System;
using System.IO;
using Aspose.Words.Cloud.Sdk;
using Aspose.Words.Cloud.Sdk.Model;
using Aspose.Words.Cloud.Sdk.Model.Requests;

namespace Aspose.Words.Cloud.Examples.CSharp
{
	public class PopulateMailMergeTemplateWithHTMLData
	{
		public static void Run()
		{
			WordsApi wordsApi = new WordsApi(Constants.AppKey, Constants.AppSID);

			try
			{
				string fileName = "template.doc";
				string destName = "Out_PostDocumentExecuteMailMergeWithHTMLData.docx";

				// 將原始文檔上傳至雲端存儲
				wordsApi.UploadFile(new UploadFileRequest(File.Open("..\\..\\..\\Resources\\" + fileName, FileMode.Open), fileName, Constants.MYStorage));

				string data = File.ReadAllText("..\\..\\..\\Resources\\TestPostDocumentExecuteMailMerge.txt", System.Text.Encoding.UTF8);
				ExecuteMailMergeRequest request = new ExecuteMailMergeRequest(fileName, data, null, Constants.MYStorage, null, null, null, null, null, null, destName);
				DocumentResponse result = wordsApi.ExecuteMailMerge(request);

			}
			catch (Exception e)
			{
				Console.WriteLine(e.ToString());
			}
		}
	}
}

在郵件合併期間插入影像

您也可以在合併欄位中插入影像。可使用「%」、「px」或「」(比例縮放)設定影像的比例因子。郵件合併期間插入影像的程式碼如下:

// 如需完整範例和資料文件,請造訪 https://github.com/aspose-words-cloud/aspose-words-cloud-dotnet

string MyAppKey = ""; // Get AppKey and AppSID from https://dashboard.aspose.cloud/
string MyAppSid = ""; // Get AppKey and AppSID from https://dashboard.aspose.cloud/

WordsApi wordsApi = new WordsApi(MyAppKey, MyAppSid);
StorageApi storageApi = new StorageApi(MyAppKey, MyAppSid);

var fileName = "TestMailMergeWithImages.doc";
var destFileName = "TestMailMergeWithImages_Out.docx";
var data = File.ReadAllText(WordsExamples.PathToDataFiles + @"\DocumentActions\MailMerge\" + "MailMergeData.txt");
string folder = null; // File exists at the root of the storage

// 將輸入文檔上傳到雲端存儲
PutCreateRequest request = new PutCreateRequest(fileName, File.OpenRead(WordsExamples.PathToDataFiles + @"\DocumentActions\MailMerge\" + fileName), null, null);
storageApi.PutCreate(request);

var executeMailMergeRequest = new PostDocumentExecuteMailMergeRequest(fileName, data, folder, destFileName: destFileName, withRegions: false);
var actual = wordsApi.PostDocumentExecuteMailMerge(executeMailMergeRequest);

雲端SDK

儘管上面的程式碼是在 .NET 中編寫的,但 Aspose.Words Cloud SDK 有五種不同語言版本:.NET、Java、Ruby、Python 和 Node.js。因此,您可以方便地使用這些語言中的任何一種來呼叫郵件合併 API。

建議貼文: