邮件如何使用C#在Word文档中进行邮件合并?Aspose.Words解析攻略( 二 )


以下是将用XML数据填充的邮件合并模板 。
邮件如何使用C#在Word文档中进行邮件合并?Aspose.Words解析攻略
本文插图
以下是执行邮件合并后得到的Word文档的第1页 。
邮件如何使用C#在Word文档中进行邮件合并?Aspose.Words解析攻略
本文插图
合并字段的自定义格式
.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 &lt 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 &lt 10 i++) { DataRow datarow = dataTable.NewRow() dataTable.Rows.Add(datarow) datarow[0] = "Company " + i.ToString() datarow[1] = "Contact " + i.ToString() } return dataTable }


推荐阅读