Word处理控件Aspose.Words功能演示:使用C#或VB.NET在Word文档中进行邮件合并

在许多情况下,使用PDF文档时,您需要进行更改:复制,粘贴,拖放特定的PDF内容,例如文本,图像,表格和图表。只要您要处理文档的一小部分,就可以在同一PDF文件中手动执行这些选项。但是,如果您想在更复杂的情况下执行编辑选项,例如创建数字签名,合并多个PDF文档或重新处理PDF文件中的所有文本,该怎么办?

Aspose.Words for .NET是功能丰富且功能强大的Word API,它提供了所有基本以及扩展的MS Word Mail Merge功能。它使您可以在Windows窗体,ASP.NET Web应用程序或任何.NET / .NET Core应用程序中生成信函,信封,报告,发票和其他类型的文档。

在本文中,将展示如何在不使用MS Word或Office Interop的情况下使用C#或VB.NET执行MS Word邮件合并。本文由以下部分组成:

  • 使用C#在Word文档中执行邮件合并
  • 使用XML数据源的邮件合并
  • 合并字段的自定义格式
  • 区域合并邮件
  • 嵌套邮件合并区域

点击下载最新版Aspose.Words for .NET(技术交流761297826)icon-default.png?t=M7J4https://www.evget.com/product/564/download

邮件合并是自动生成报告,信件,信封,发票和其他类型的文档的方式。MS Word中的邮件合并允许您创建包含合并字段的模板文档,然后使用数据源中的记录填充这些字段。要了解邮件合并,假设您必须向十个不同的人发送一封信,并且仅姓名和地址字段将被更新。在这种情况下,只需创建字母的模板,然后通过使用数据源填充名称和地址合并字段来动态生成字母。

可以从任何数据源(例如XML,JSON或数据库)中获取邮件合并的数据。就Aspose.Words for .NET而言,可以使用ADO.NET支持的任何数据源。可以将数据加载到DataSet,DataTable,DataView或值数组中。

邮件合并模板是包含合并字段的文档。执行“邮件合并”时,这些字段然后用数据源中的数据填充。模板文档不需要是模板格式,可以是DOC / DOCX文档。这是您可以为邮件合并准备模板的方法。

  • 在MS Word中打开您的文档或创建一个新文档。
  • 将光标放在要添加合并字段的位置。
  • 从 插入 菜单中选择 字段 选项。
  • 从 字段名称 列表中,选择 MergeField。
  • 在字段名称中为合并字段输入名称,然后按 确定。
  • 保存文档。

以下是示例模板文档的屏幕截图。

使用C#在Word文档中执行邮件合并

准备好模板后,可以执行邮件合并以生成文档。以下是在上述模板上执行邮件合并的步骤。

  • 使用Document类加载模板文档。
  • 设置必需的邮件合并选项,例如Document.MailMerge.TrimWhitespaces。
  • 使用Document.MailMerge.Execute()方法执行邮件合并,并将数据源作为参数传递。
  • 使用Document.Save(String)方法保存生成的文档。

下面的代码示例演示如何使用C#中的值数组执行MS Word邮件合并。

// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting(); 
// Open an existing document.
Document doc = new Document(dataDir + "MailMerge.ExecuteArray.doc");

// Trim trailing and leading whitespaces mail merge values
doc.MailMerge.TrimWhitespaces = false;

// Fill the fields in the document with user data.
doc.MailMerge.Execute(
    new string[] { "FullName", "Company", "Address", "Address2", "City" },
    new object[] { "James Bond", "MI5 Headquarters", "Milbank", "", "London" });

dataDir = dataDir + "MailMerge.ExecuteArray_out.doc";
// Send the document in Word format to the client browser with an option to save to disk or open inside the current browser.
doc.Save(dataDir);

邮件合并后的Word文档

使用C#中的XML数据源执行邮件合并

XML文件被广泛用于保存以及导入/导出数据。Aspose.Words for .NET还支持XML作为邮件合并的数据源。只需将XML读入DataSet对象并执行邮件合并。以下是我们将要使用的示例XML文件。

下面的代码示例从XML数据源获取数据,并使用C#执行邮件合并。

// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting(); 

// Create the Dataset and read the XML.
DataSet customersDs = new DataSet();
customersDs.ReadXml(dataDir + "Customers.xml");

string fileName = "TestFile XML.doc";
// Open a template document.
Document doc = new Document(dataDir + fileName);

// Execute mail merge to fill the template with data from XML using DataTable.
doc.MailMerge.Execute(customersDs.Tables["Customer"]);

dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the output document.
doc.Save(dataDir);

以下是将用XML数据填充的邮件合并模板。

以下是执行邮件合并后得到的Word文档的第1页。

合并字段的自定义格式

.NET的Aspose.Words使您在执行过程中对“邮件合并”有更多控制。该MailMerge.FieldMergingCallback属性允许您遇到任何合并域时自定义邮件合并。MailMerge.FieldMergingCallback接受实现IFieldMergingCallback.FieldMerging和IFieldMergingCallback.ImageFieldMerging方法的类。

下面的代码示例演示如何自定义“邮件合并”操作并将格式应用于此模板中的单元格。

// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting(); 
Document doc = new Document(dataDir + "MailMerge.AlternatingRows.doc");

// Add a handler for the MergeField event.
doc.MailMerge.FieldMergingCallback = new HandleMergeFieldAlternatingRows();

// Execute mail merge with regions.
DataTable dataTable = GetSuppliersDataTable();
doc.MailMerge.ExecuteWithRegions(dataTable);
dataDir = dataDir + "MailMerge.AlternatingRows_out.doc";
doc.Save(dataDir);

以下是HandleMergeFieldAlternatingRows类的实现。

private class HandleMergeFieldAlternatingRows : IFieldMergingCallback
{
    // Called for every merge field encountered in the document.
    /// We can either return some data to the mail merge engine or do something
    /// Else with the document. In this case we modify cell formatting.
    ///void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
    {
        if (mBuilder == null)
            mBuilder = new DocumentBuilder(e.Document);

        // This way we catch the beginning of a new row.
        if (e.FieldName.Equals("CompanyName"))
        {
            // Select the color depending on whether the row number is even or odd.
            Color rowColor;
            if (IsOdd(mRowIdx))
                rowColor = Color.FromArgb(213, 227, 235);
            else
                rowColor = Color.FromArgb(242, 242, 242);

            // There is no way to set cell properties for the whole row at the moment,
            // So we have to iterate over all cells in the row.
            for (int colIdx = 0; colIdx < 4; colIdx++) { mBuilder.MoveToCell(0, mRowIdx, colIdx, 0); mBuilder.CellFormat.Shading.BackgroundPatternColor = rowColor; } mRowIdx++; } } void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args) { // Do nothing. } private DocumentBuilder mBuilder; private int mRowIdx; } // Returns true if the value is odd; false if the value is even. ///private static bool IsOdd(int value) { // The code is a bit complex, but otherwise automatic conversion to VB does not work. return ((value / 2) * 2).Equals(value); } // Create DataTable and fill it with data. /// In real life this DataTable should be filled from a database. ///private static DataTable GetSuppliersDataTable() { DataTable dataTable = new DataTable("Suppliers"); dataTable.Columns.Add("CompanyName"); dataTable.Columns.Add("ContactName"); for (int i = 0; i < 10; i++) { DataRow datarow = dataTable.NewRow(); dataTable.Rows.Add(datarow); datarow[0] = "Company " + i.ToString(); datarow[1] = "Contact " + i.ToString(); } return dataTable; }

使用C#将邮件与区域合并

在某些情况下,您需要填充并重复Word文档中的特定区域。在这种情况下,可以对区域使用邮件合并。若要创建区域,您需要指定区域的开始和结束,然后Mail Megre将为数据源中的每个记录重复该区域。例如,以下模板包含两个区域,分别是Orders和OrderDetails,它们具有合并字段«TableStart:Orders»,«TableEnd:Orders»和«TableStart:OrderDetails»,«TableEnd:OrderDetails»。

以下是在上述模板的区域上执行Mail Megre的代码示例。

// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting();
string fileName = "MailMerge.ExecuteWithRegions.doc";
Document doc = new Document(dataDir + fileName);
 
// Use DataTable as a data source.
int orderId = 10444;
DataTable orderTable = GetTestOrder(orderId);
doc.MailMerge.ExecuteWithRegions(orderTable);
 
// Instead of using DataTable, you can create a DataView for custom sort or filter and then mail merge.
DataView orderDetailsView = new DataView(GetTestOrderDetails(orderId));
orderDetailsView.Sort = "ExtendedPrice DESC";
 
// Execute the mail merge operation.
doc.MailMerge.ExecuteWithRegions(orderDetailsView);
 
// Save the merged document.
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
doc.Save(dataDir);

以下是从数据库读取数据的方法。

private static DataTable GetTestOrder(int orderId)
{
    DataTable table = ExecuteDataTable(string.Format(
        "SELECT * FROM AsposeWordOrders WHERE OrderId = {0}", orderId));
    table.TableName = "Orders";
    return table;
}
private static DataTable GetTestOrderDetails(int orderId)
{
    DataTable table = ExecuteDataTable(string.Format(
        "SELECT * FROM AsposeWordOrderDetails WHERE OrderId = {0} ORDER BY ProductID", orderId));
    table.TableName = "OrderDetails";
    return table;
}
// Utility function that creates a connection, command, 
/// Executes the command and return the result in a DataTable.
///private static DataTable ExecuteDataTable(string commandText)
{
    // Open the database connection.
    string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
        RunExamples.GetDataDir_Database() + "Northwind.mdb";
    OleDbConnection conn = new OleDbConnection(connString);
    conn.Open();

    // Create and execute a command.
    OleDbCommand cmd = new OleDbCommand(commandText, conn);
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
    DataTable table = new DataTable();
    da.Fill(table);

    // Close the database.
    conn.Close();

    return table;
}

嵌套邮件合并区域

通常,我们在数据源中拥有的数据以关系的形式出现。例如,表“ Order”将与“ OrderDetails”具有一对多关系,该关系将保留订单中的项目记录。为了处理此类父子关系,使用了嵌套的邮件合并。以下是非常适合这种情况的示例发票模板。

以下是将用于嵌套邮件合并的示例XML数据源。

而此XML 的OrderSchema.xsd为:

下面的代码示例用于使用C#执行嵌套的邮件合并。

// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_MailMergeAndReporting(); 
            
// Create the Dataset and read the XML.
DataSet pizzaDs = new DataSet();

// Note: The Datatable.TableNames and the DataSet.Relations are defined implicitly by .NET through ReadXml.
// To see examples of how to set up relations manually check the corresponding documentation of this sample
pizzaDs.ReadXml(dataDir + "CustomerData.xml");

string fileName = "Invoice Template.doc";
// Open the template document.
Document doc = new Document(dataDir + fileName);

// Trim trailing and leading whitespaces mail merge values
doc.MailMerge.TrimWhitespaces = false;

// Execute the nested mail merge with regions
doc.MailMerge.ExecuteWithRegions(pizzaDs);

dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the output to file
doc.Save(dataDir);

邮件合并后的Word文档。下面是执行邮件合并后生成的Word文档的第一页。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值