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


使用C#将邮件与区域合并
在某些情况下 , 您需要填充并重复Word文档中的特定区域 。 在这种情况下 , 可以对区域使用邮件合并 。 若要创建区域 , 您需要指定区域的开始和结束 , 然后Mail Megre将为数据源中的每个记录重复该区域 。 例如 , 以下模板包含两个区域 , 分别是Orders和OrderDetails , 它们具有合并字段?TableStart:Orders? , ?TableEnd:Orders?和?TableStart:OrderDetails? , ?TableEnd:OrderDetails? 。
邮件如何使用C#在Word文档中进行邮件合并?Aspose.Words解析攻略
本文插图
以下是在上述模板的区域上执行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 = 10444DataTable 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.0Data 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”具有一对多关系 , 该关系将保留订单中的项目记录 。 为了处理此类父子关系 , 使用了嵌套的邮件合并 。 以下是非常适合这种情况的示例发票模板 。
邮件如何使用C#在Word文档中进行邮件合并?Aspose.Words解析攻略
本文插图
以下是将用于嵌套邮件合并的示例XML数据源 。
邮件如何使用C#在Word文档中进行邮件合并?Aspose.Words解析攻略
本文插图
而此XML 的OrderSchema.xsd为:
邮件如何使用C#在Word文档中进行邮件合并?Aspose.Words解析攻略


推荐阅读