邮件合并是 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. 从字段名称列表中,选择 MergeField。
  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)

举个例子,看一下 Item Catalog 演示。以下是为邮件合并准备的区域片段:

邮件合并

注意标记字段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

// 将输入文档上传至 Cloud 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 }}

Object.Attribute 语法

您可以使用以下语法轻松合并字段的属性:

  {{ 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 语句结合使用。只有当与其关联的布尔表达式为真时,才会执行 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");

// 将输入文档上传至 Cloud Storage
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

// 将输入文档上传至 Cloud 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 SDKs 有五种不同的语言版本:.NET、Java、Ruby、Python 和 Node.js。因此,您可以方便地使用其中任何一种语言调用邮件合并 API。

建议发帖: