2012-12-09 29 views
4

創建標籤的最佳方式是使用現有的行業標準工具,例如Microsoft word。郵件合併到單詞中

如何執行此操作並設置運輸標籤?

我不確定如何將合併字段映射到數據網格視圖列。這是我到目前爲止的代碼:

// Create a new empty document. 
DocumentModel document = new DocumentModel(); 

// Add document content. 
document.Sections.Add(
    new Section(document, 
     new Paragraph(document, 
      new Field(document, FieldType.MergeField, "FullName")))); 

// Save the document to a file and open it with Microsoft Word. 
document.Save("TemplateDocument.docx"); 
// If document appears empty in Microsoft Word, press Alt + F9. 
Process.Start("TemplateDocument.docx"); 

// Initialize mail merge data source. 
var dataSource = new { FullName = "John Doe" }; 

// Execute mail merge. 
document.MailMerge.Execute(dataSource); 

// Save the document to a file and open it with Microsoft Word. 
document.Save("Document.docx"); 
Process.Start("Document.docx"); 
+1

你的問題是非常不清楚的。 – SLaks

+1

如果您以編程方式生成文檔,則根本不需要使用郵件合併。 – SLaks

回答

1

首先,您應該學習如何製作Label模板文檔。 例如,通過以下視頻教程:www.youtube.com/watch?v=tIg70utT72Q

在保存模板文檔之前,請刪除郵件合併過程中創建的郵件合併數據源,因爲您將使用.NET對象作爲郵件合併數據源。 要刪除郵件合併數據源去郵件選項卡 - >啓動郵件合併 - >選擇普通Word文檔,就像在圖像: Remove mail merge data source

將文檔保存到一個文件,例如「LabelTemplate.docx」。 當你按下Alt + F9你應該會看到類似下面的圖像中的域代碼: Label template content

現在你已準備好與GemBox.Document組件(你在問題中使用的代碼)進行編程郵件合併。 這裏是一個C#代碼如何執行郵件合併:

// Set licensing info. 
ComponentInfo.SetLicense("FREE-LIMITED-KEY"); 
ComponentInfo.FreeLimitReached += (sender, e) => e.FreeLimitReachedAction = FreeLimitReachedAction.ContinueAsTrial; 

// Create mail merge data source. 
// You should use DataGridView.DataSource property - it will return DataView or DataTable that is data-bound to your DataGridView. 
var dataTable = new DataTable() 
{ 
    Columns = 
    { 
     new DataColumn("Name"), 
     new DataColumn("Surname"), 
     new DataColumn("Company") 
    }, 
    Rows = 
    { 
     { "John", "Doe", "ACME" }, 
     { "Fred", "Nurk", "ACME" }, 
     { "Hans", "Meier", "ACME" } 
    } 
}; 

var document = DocumentModel.Load("LabelTemplate.docx", LoadOptions.DocxDefault); 

// Use this if field names and data column names differ. If they are the same (case-insensitive), then you don't need to define mappings explicitly. 
document.MailMerge.FieldMappings.Add("First_Name", "Name"); 
document.MailMerge.FieldMappings.Add("Last_Name", "Surname"); 
document.MailMerge.FieldMappings.Add("Company_Name", "Company"); 

// Execute mail merge. Each mail merge field will be replaced with the data from the data source's appropriate row and column. 
document.MailMerge.Execute(dataTable); 

// Remove any left mail merge field. 
document.MailMerge.RemoveMergeFields(); 

// Save resulting document to a file. 
document.Save("Labels.docx"); 

由此產生的「Labels.docx」的文件應該是這樣的: Label mail merge result

因爲組件中使用

促銷頭部被自動添加試用模式。 GemBox.Document mail merge非常靈活,它支持hierarchical mail merge,通過處理FieldMerging event或指定merge field format string來自定義每個字段的合併。

+0

非常感謝您的支持,它完全按照您的解釋工作,並且非常有幫助。你們好棒! –