如何在 C# 中對 Word 文件進行合併列印
IronWord 透過將Word範本中的MERGEFIELD佔位符替換為從字典、DataTable/DataRow/DataSet物件或重複區域表格中擷取的資料,來在C#中執行郵件合併,且無需Microsoft Office Interop。在Microsoft Word或任何相容工具中建立的合併欄位將自動偵測。
郵件合併是大規模產生個性化文件的標準方法:如表格信件、發票、證書、合同和報告等,它們共用一個模板但因收件人不同而區別。 您不必逐一手動編輯每個文件,而是創作一個含有合併字段的.docx範本,然後讓IronWord從您的數據來源填充它們。 每個操作都是通過WordDocument.MailMerge入口點實現的。
載入包含MERGEFIELD佔位符的範本,將欄位名稱和值的字典傳遞給Execute,並儲存結果。
-
1使用 IronWord 安裝 NuGet Package Manager
-
2複製並運行這段程式碼。
WordDocument doc = new WordDocument("template.docx"); doc.MailMerge.Execute(new Dictionary<string, string> { { "FirstName", "Jane" }, { "Company", "Acme Corp" } }); doc.SaveAs("output.docx");Dim doc As New WordDocument("template.docx") doc.MailMerge.Execute(New Dictionary(Of String, String) From {{"FirstName", "Jane"}, {"Company", "Acme Corp"}}) doc.SaveAs("output.docx")Dim doc As New WordDocument("template.docx") doc.MailMerge.Execute(New Dictionary(Of String, String) From {{"FirstName", "Jane"}, {"Company", "Acme Corp"}}) doc.SaveAs("output.docx") -
3部署到您的生產環境進行測試
立即在您的項目中開始使用 IronWord,並使用 免費試用
最小工作流程(5 個步驟)
- 從NuGet下載Word郵件合併C#庫
- 創建一個含有
MERGEFIELD佔位符的Word模板 - 使用
WordDocument構造函數加載模板 - 使用您的數據來源調用
MailMerge.Execute或MailMerge.ExecuteWithRegions - 儲存填充過的文件
我如何從字典中進行郵件合併?
最簡單的數據來源是按合併字段名稱鍵入的IDictionary<string, string>。 Execute替換了與鍵匹配的所有字段。
using IronWord;
using System.Collections.Generic;
// Load a template containing MERGEFIELD placeholders
WordDocument doc = new WordDocument("template.docx");
// Replace each field whose name matches a dictionary key
doc.MailMerge.Execute(new Dictionary<string, string>
{
{ "FirstName", "Jane" },
{ "LastName", "Smith" },
{ "Company", "Acme Corp" }
});
doc.SaveAs("output.docx");using IronWord;
using System.Collections.Generic;
// Load a template containing MERGEFIELD placeholders
WordDocument doc = new WordDocument("template.docx");
// Replace each field whose name matches a dictionary key
doc.MailMerge.Execute(new Dictionary<string, string>
{
{ "FirstName", "Jane" },
{ "LastName", "Smith" },
{ "Company", "Acme Corp" }
});
doc.SaveAs("output.docx");Imports IronWord
Imports System.Collections.Generic
' Load a template containing MERGEFIELD placeholders
Dim doc As New WordDocument("template.docx")
' Replace each field whose name matches a dictionary key
doc.MailMerge.Execute(New Dictionary(Of String, String) From {
{"FirstName", "Jane"},
{"LastName", "Smith"},
{"Company", "Acme Corp"}
})
doc.SaveAs("output.docx")Imports IronWord
Imports System.Collections.Generic
' Load a template containing MERGEFIELD placeholders
Dim doc As New WordDocument("template.docx")
' Replace each field whose name matches a dictionary key
doc.MailMerge.Execute(New Dictionary(Of String, String) From {
{"FirstName", "Jane"},
{"LastName", "Smith"},
{"Company", "Acme Corp"}
})
doc.SaveAs("output.docx")MailMerge.Options.CaseInsensitiveFieldNames = false以要求精確大小寫匹配。您也可以提供兩組平行的字段名稱和值的序列:
using IronWord;
WordDocument doc = new WordDocument("template.docx");
// Merge from two parallel sequences of field names and values
doc.MailMerge.Execute(
new[] { "FirstName", "LastName" },
new[] { "Jane", "Smith" });
doc.SaveAs("output.docx");using IronWord;
WordDocument doc = new WordDocument("template.docx");
// Merge from two parallel sequences of field names and values
doc.MailMerge.Execute(
new[] { "FirstName", "LastName" },
new[] { "Jane", "Smith" });
doc.SaveAs("output.docx");Imports IronWord
Dim doc As New WordDocument("template.docx")
' Merge from two parallel sequences of field names and values
doc.MailMerge.Execute(
New String() {"FirstName", "LastName"},
New String() {"Jane", "Smith"})
doc.SaveAs("output.docx")Imports IronWord
Dim doc As New WordDocument("template.docx")
' Merge from two parallel sequences of field names and values
doc.MailMerge.Execute(
New String() {"FirstName", "LastName"},
New String() {"Jane", "Smith"})
doc.SaveAs("output.docx")Execute(fieldNames, values)當兩個序列長度不一致時會丟擲ArgumentException。我如何從DataTable或DataRow中進行郵件合併?
當資料來自資料庫或現有DataSet時,將DataTable或DataRow直接傳遞給Execute。 合併字段名稱對應於列名稱。 Execute(DataTable)使用表格第一行的值,而Execute(DataRow)使用行的父表格的欄名。
using IronWord;
using System.Data;
// Build a DataTable, for example from a database query
DataTable table = new DataTable();
table.Columns.Add("FirstName");
table.Columns.Add("LastName");
DataRow row = table.NewRow();
row["FirstName"] = "Jane";
row["LastName"] = "Smith";
table.Rows.Add(row);
WordDocument doc = new WordDocument("template.docx");
// Merge-field names are matched to the row's column names
doc.MailMerge.Execute(row);
doc.SaveAs("output.docx");using IronWord;
using System.Data;
// Build a DataTable, for example from a database query
DataTable table = new DataTable();
table.Columns.Add("FirstName");
table.Columns.Add("LastName");
DataRow row = table.NewRow();
row["FirstName"] = "Jane";
row["LastName"] = "Smith";
table.Rows.Add(row);
WordDocument doc = new WordDocument("template.docx");
// Merge-field names are matched to the row's column names
doc.MailMerge.Execute(row);
doc.SaveAs("output.docx");Imports IronWord
Imports System.Data
' Build a DataTable, for example from a database query
Dim table As New DataTable()
table.Columns.Add("FirstName")
table.Columns.Add("LastName")
Dim row As DataRow = table.NewRow()
row("FirstName") = "Jane"
row("LastName") = "Smith"
table.Rows.Add(row)
Dim doc As New WordDocument("template.docx")
' Merge-field names are matched to the row's column names
doc.MailMerge.Execute(row)
doc.SaveAs("output.docx")Imports IronWord
Imports System.Data
' Build a DataTable, for example from a database query
Dim table As New DataTable()
table.Columns.Add("FirstName")
table.Columns.Add("LastName")
Dim row As DataRow = table.NewRow()
row("FirstName") = "Jane"
row("LastName") = "Smith"
table.Rows.Add(row)
Dim doc As New WordDocument("template.docx")
' Merge-field names are matched to the row's column names
doc.MailMerge.Execute(row)
doc.SaveAs("output.docx")我如何填充重複表格區域?
重複區域將一個模板行變成多行,非常適合使用於發票項目或訂單清單。 在範本中,將重複內容包裹在命名為TableStart:RegionName和TableEnd:RegionName的兩個標記欄位之間。 然後調用ExecuteWithRegions,其會對匹配表的每一行重複區域的內容。
ExecuteWithRegions接受完整DataSet(展開名稱與表格匹配的每個區域)、單一DataTable(展開名稱與dataTable.TableName匹配的區域),或區域名稱與DataTable一起使用。
using IronWord;
using System.Collections.Generic;
using System.Data;
// One DataTable per repeating region, named to match the TableStart/TableEnd markers
DataTable orders = new DataTable("Orders");
orders.Columns.Add("Item");
orders.Columns.Add("Qty");
orders.Rows.Add("Widget A", "3");
orders.Rows.Add("Widget B", "1");
DataSet ds = new DataSet();
ds.Tables.Add(orders);
WordDocument doc = new WordDocument("invoice-template.docx");
// Expand the repeating region once per row, then fill standard fields
doc.MailMerge.ExecuteWithRegions(ds);
doc.MailMerge.Execute(new Dictionary<string, string> { { "CustomerName", "Jane Smith" } });
doc.SaveAs("invoice.docx");using IronWord;
using System.Collections.Generic;
using System.Data;
// One DataTable per repeating region, named to match the TableStart/TableEnd markers
DataTable orders = new DataTable("Orders");
orders.Columns.Add("Item");
orders.Columns.Add("Qty");
orders.Rows.Add("Widget A", "3");
orders.Rows.Add("Widget B", "1");
DataSet ds = new DataSet();
ds.Tables.Add(orders);
WordDocument doc = new WordDocument("invoice-template.docx");
// Expand the repeating region once per row, then fill standard fields
doc.MailMerge.ExecuteWithRegions(ds);
doc.MailMerge.Execute(new Dictionary<string, string> { { "CustomerName", "Jane Smith" } });
doc.SaveAs("invoice.docx");Imports IronWord
Imports System.Collections.Generic
Imports System.Data
' One DataTable per repeating region, named to match the TableStart/TableEnd markers
Dim orders As New DataTable("Orders")
orders.Columns.Add("Item")
orders.Columns.Add("Qty")
orders.Rows.Add("Widget A", "3")
orders.Rows.Add("Widget B", "1")
Dim ds As New DataSet()
ds.Tables.Add(orders)
Dim doc As New WordDocument("invoice-template.docx")
' Expand the repeating region once per row, then fill standard fields
doc.MailMerge.ExecuteWithRegions(ds)
doc.MailMerge.Execute(New Dictionary(Of String, String) From {{"CustomerName", "Jane Smith"}})
doc.SaveAs("invoice.docx")Imports IronWord
Imports System.Collections.Generic
Imports System.Data
' One DataTable per repeating region, named to match the TableStart/TableEnd markers
Dim orders As New DataTable("Orders")
orders.Columns.Add("Item")
orders.Columns.Add("Qty")
orders.Rows.Add("Widget A", "3")
orders.Rows.Add("Widget B", "1")
Dim ds As New DataSet()
ds.Tables.Add(orders)
Dim doc As New WordDocument("invoice-template.docx")
' Expand the repeating region once per row, then fill standard fields
doc.MailMerge.ExecuteWithRegions(ds)
doc.MailMerge.Execute(New Dictionary(Of String, String) From {{"CustomerName", "Jane Smith"}})
doc.SaveAs("invoice.docx")ExecuteWithRegions僅填入重複區域。 為了填充區域之外的標準合併字段,在擴展區域之後調用Execute(...),如上所示。我如何檢查模板的合併字段?
在合併之前,您可以發現模板中包含的內容,這對於驗證模板或動態生成數據源很有用。
GetFieldNames()返回所有值樣式合併字段的名稱,按文檔順序並去重。GetRegionNames()返回文件中聲明的所有TableStart區域名稱。GetFields()返回每個欄位,包括TableStart/TableEnd標記,作為MergeField物件。
using IronWord;
using System.Collections.Generic;
WordDocument doc = new WordDocument("template.docx");
// Discover the merge fields and regions before merging
IReadOnlyList<string> fieldNames = doc.MailMerge.GetFieldNames();
IReadOnlyList<string> regionNames = doc.MailMerge.GetRegionNames();
// fieldNames: ["FirstName", "LastName", "Company"]
// regionNames: ["Orders", "LineItems"]using IronWord;
using System.Collections.Generic;
WordDocument doc = new WordDocument("template.docx");
// Discover the merge fields and regions before merging
IReadOnlyList<string> fieldNames = doc.MailMerge.GetFieldNames();
IReadOnlyList<string> regionNames = doc.MailMerge.GetRegionNames();
// fieldNames: ["FirstName", "LastName", "Company"]
// regionNames: ["Orders", "LineItems"]Imports IronWord
Imports System.Collections.Generic
Dim doc As New WordDocument("template.docx")
' Discover the merge fields and regions before merging
Dim fieldNames As IReadOnlyList(Of String) = doc.MailMerge.GetFieldNames()
Dim regionNames As IReadOnlyList(Of String) = doc.MailMerge.GetRegionNames()
' fieldNames: ["FirstName", "LastName", "Company"]
' regionNames: ["Orders", "LineItems"]Imports IronWord
Imports System.Collections.Generic
Dim doc As New WordDocument("template.docx")
' Discover the merge fields and regions before merging
Dim fieldNames As IReadOnlyList(Of String) = doc.MailMerge.GetFieldNames()
Dim regionNames As IReadOnlyList(Of String) = doc.MailMerge.GetRegionNames()
' fieldNames: ["FirstName", "LastName", "Company"]
' regionNames: ["Orders", "LineItems"]每個MergeField皆公開其Name,完整的Instruction文本如文檔中所儲存(例如MERGEFIELD FirstName \* MERGEFORMAT),僅為區域標記設置的RegionName(例如"Orders"來自"TableStart:Orders"),以及分類為Value的Kind(文本已用數據值替換),TableStart或TableEnd(重複區域的邊界),或NextRecord(在相同模板主體內進入下一個數據記錄的NEXT欄位)。
我如何控制未匹配字段和空值?
合併行為是通過MailMerge.Options配置的:
| 選項 | Default | 行為 |
|---|---|---|
RemoveUnusedFields | true | 移除在數據源中無匹配鍵的合併字段。 設置為false以保留它們的原位。 |
RemoveUnusedRegions | true | 移除在資料源中沒有匹配表格的TableStart/TableEnd區域。 |
NullValueReplacement | "" | 當數據源對字段提供null值時進行文本替換。 |
CaseInsensitiveFieldNames | true | 在匹配字段名稱時忽略大小寫,匹配Microsoft Word的行為。 |
using IronWord;
using System.Collections.Generic;
WordDocument doc = new WordDocument("template.docx");
// Keep unmatched fields in the output instead of removing them
doc.MailMerge.Options.RemoveUnusedFields = false;
doc.MailMerge.Execute(new Dictionary<string, string> { { "FirstName", "Jane" } });
doc.SaveAs("partial-output.docx");using IronWord;
using System.Collections.Generic;
WordDocument doc = new WordDocument("template.docx");
// Keep unmatched fields in the output instead of removing them
doc.MailMerge.Options.RemoveUnusedFields = false;
doc.MailMerge.Execute(new Dictionary<string, string> { { "FirstName", "Jane" } });
doc.SaveAs("partial-output.docx");Imports IronWord
Imports System.Collections.Generic
Dim doc As New WordDocument("template.docx")
' Keep unmatched fields in the output instead of removing them
doc.MailMerge.Options.RemoveUnusedFields = False
doc.MailMerge.Execute(New Dictionary(Of String, String) From {{"FirstName", "Jane"}})
doc.SaveAs("partial-output.docx")Imports IronWord
Imports System.Collections.Generic
Dim doc As New WordDocument("template.docx")
' Keep unmatched fields in the output instead of removing them
doc.MailMerge.Options.RemoveUnusedFields = False
doc.MailMerge.Execute(New Dictionary(Of String, String) From {{"FirstName", "Jane"}})
doc.SaveAs("partial-output.docx")若無數據源需直接進行簡單的值替換,請參閱如何替換Word文件中的文字。
常見問題
使用IronWord在C#中進行郵件合併是什麼?
在C#中使用IronWord進行郵件合併允許您將Word範本中的MERGEFIELD佔位符與來自字典、DataTable、DataRow或DataSet對象的數據進行填充,從而創建個性化的文件,如發票和報告。
IronWord如何在沒有Microsoft Office的情況下執行郵件合併?
IronWord通過加載Word範本並通過WordDocument.MailMerge入口執行合併來實現不需要Microsoft Office的郵件合併,將佔位符替換為數據。
我可以使用字典來與IronWord進行郵件合併嗎?
是的,IronWord允許通過在Execute方法中匹配域名與字典鍵進行郵件合併。
如何使用IronWord與DataTable進行郵件合併?
您可以在IronWord中通過將DataTable傳遞給Execute方法來執行郵件合併,該方法使用第一列的欄名來匹配範本中的合併域。
什麼是郵件合併中的重複區域,IronWord如何處理它們?
郵件合併中的重複區域是可以根據數據列擴展的部分,非常適合如發票列目。IronWord通過在範本中使用TableStart和TableEnd標記,並使用ExecuteWithRegions方法來處理它們。
如何使用IronWord檢查範本的合併域?
您可以使用IronWord的GetFieldNames和GetRegionNames方法來檢查範本中的合併域和區域名稱,有助於驗證範本或動態創建數據來源。
IronWord如何在郵件合併中處理未匹配的字段和空值?
IronWord提供選項,如RemoveUnusedFields、RemoveUnusedRegions和NullValueReplacement,在MailMerge.Options中控制未匹配字段和空值的行為。
使用IronWord郵件合併Word文檔的最小工作流程是什麼?
最小工作流程包括下載IronWord程式庫、編寫Word範本、使用WordDocument加載範本、使用您的數據執行合併,並保存填充的文件。
大小寫敏感性如何影響IronWord郵件合併中的字段名匹配?
在IronWord中,郵件合併的字段名查找默認情況下不區分大小寫,與Microsoft Word類似。您可以使用MailMerge.Options.CaseInsensitiveFieldNames調整此行為。
IronWord如何支持合併多個文檔或範本?
IronWord允許您通過使用相同範本與不同數據或通過使用ExecuteWithRegions方法來重複數據項目快速填充多個文檔。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。