翻譯|使用教程|編輯:李顯亮|2020-07-16 11:18:14.247|閱讀 441 次
概述:在本文中,將展示如何在不使用MS Word或Office Interop的情況下使用C?;騐B.NET執行MS Word郵件合并。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
在許多情況下,使用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?;騐B.NET執行MS Word郵件合并。本文由以下部分組成:
>>Aspose.Words for .NET已經更新至v20.7,Aspose.Words for .Net更新至新版本v20.7,添加了新節點以處理多節結構化文檔標簽,改進了SmartArt冷渲染的性能,RevisionOptions類擴展了新的屬性,點擊下方按鈕下載最新版。
郵件合并是自動生成報告,信件,信封,發票和其他類型的文檔的方式。MS Word中的郵件合并允許您創建包含合并字段的模板文檔,然后使用數據源中的記錄填充這些字段。要了解郵件合并,假設您必須向十個不同的人發送一封信,并且僅姓名和地址字段將被更新。在這種情況下,只需創建字母的模板,然后通過使用數據源填充名稱和地址合并字段來動態生成字母。
可以從任何數據源(例如XML,JSON或數據庫)中獲取郵件合并的數據。就Aspose.Words for .NET而言,可以使用ADO.NET支持的任何數據源。可以將數據加載到DataSet,DataTable,DataView或值數組中。
郵件合并模板是包含合并字段的文檔。執行“郵件合并”時,這些字段然后用數據源中的數據填充。模板文檔不需要是模板格式,可以是DOC / DOCX文檔。這是您可以為郵件合并準備模板的方法。
以下是示例模板文檔的屏幕截圖。
準備好模板后,可以執行郵件合并以生成文檔。以下是在上述模板上執行郵件合并的步驟。
下面的代碼示例演示如何使用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文檔
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; }
在某些情況下,您需要填充并重復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文檔的第一頁。
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn