C# ile Word Belgelerinde Birleşik Posta Nasıl Yapılır
IronWord, C#'de birleşik posta işlemini, Word şablonundaki MERGEFIELD yer tutucularını sözlüklerden, DataTable/DataRow/DataSet nesnelerinden veya tekrarlayan-bölge tablolarından alınan verilerle doldurarak gerçekleştirir, hepsi Microsoft Office Interop kullanılmadan. Microsoft Word'de ya da uyumlu bir araçta oluşturulan birleştirme alanları otomatik olarak algılanır.
E-posta birleştirme, ölçekte kişiselleştirilmiş belgeler oluşturmanın standart yoludur: bir şablon paylaşan, ancak alıcıya göre farklılık gösteren form mektupları, faturalar, sertifikalar, sözleşmeler ve raporlar. Her belgeyi elle düzenlemek yerine, birleştirme alanları içeren tek bir .docx şablon yazarsınız ve IronWord'un bunları veri kaynağınızdan doldurmasına izin verirsiniz. Her işlem, WordDocument.MailMerge giriş noktası üzerinden sağlanır.
İçinde MERGEFIELD yer tutucuları bulunan bir şablon yükleyin, alan adları ve değerlerinden oluşan bir sözlüğü Execute metoduna geçirin ve sonucu kaydedin.
-
1IronWord ile NuGet Package Manager'u yükleyin
-
2Bu kod parçacığını kopyalayın ve çalıştırın.
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") -
3Canlı ortamınızda test için dağıtım yapın
Projenizde IronWord'yi bugün ücretsiz deneme sürümü ile kullanmaya başlayın
Asgari İş Akışı (5 adım)
- C# e-posta birleştirme için NuGet'ten kütüphaneyi indirin
MERGEFIELDyer tutucularını içeren bir Word şablonu oluşturunWordDocumentyapıcı fonksiyonunu kullanarak şablonu yükleyin- Veri kaynağınız ile
MailMerge.ExecuteveyaMailMerge.ExecuteWithRegionsçağırın - Doldurulmuş belgeyi kaydedin
Bir Sözlükten E-posta Birleştirmesini Nasıl Yaparım?
En basit veri kaynağı, birleştirme-alanı adıyla anahtarlandırılmış bir IDictionary<string, string>'dır. Execute, adı bir anahtarla eşleşen her alanı değiştirir.
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 ayarlayın.Ayrıca, alan adları ve değerlerinden oluşan iki paralel dizi sağlayabilirsiniz:
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) iki dizi farklı uzunluklara sahip olduğunda bir ArgumentException atar.Bir DataTable veya DataRow'dan E-posta Birleştirmesini Nasıl Yaparım?
Veri bir veritabanından veya mevcut bir DataSet'den geldiğinde, bir DataTable veya DataRow direkt olarak Execute'ye aktarın. Birleştirme alanı adları sütun adları ile eşleştirilir. Execute(DataTable) tablonun ilk satırının değerlerini kullanırken, Execute(DataRow) satırın üst tablo sütun adlarını kullanır.
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")Tekrar Eden Tablo Bölgelerini Nasıl Doldururum?
Tekrar eden bölgeler, bir şablon satırını birden fazla satıra dönüştürür, bu da fatura hat öğeleri veya sipariş listeleri için idealdir. Şablonda, tekrarlayan içeriği TableStart:RegionName ve TableEnd:RegionName olarak adlandırılmış iki işaret alanı arasında sarın. Sonra, eşleşen tablonun her satırı için bölge içeriğini bir kez tekrarlayan ExecuteWithRegions çağırın.
ExecuteWithRegions, tam bir DataSet (adı bir tabloyla eşleşen her bölgeyi genişleten), tek bir DataTable (adı dataTable.TableName ile eşleşen bölgeyi genişleten) veya bir bölge adıyla birlikte bir DataTable kabul eder.
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 yalnızca tekrar eden bölgeleri doldurur. Bölgelerin dışında standart birleştirme alanlarını da doldurmak için yukarıda gösterildiği gibi Execute(...)'yi bölgeleri genişlettikten sonra çağırın.Bir Şablonun Birleştirme Alanlarını Nasıl İncelerim?
Birleştirmeden önce, bir şablonun neler içerdiğini keşfedebilir, bu da şablonları doğrulamak veya veri kaynağını dinamik olarak oluşturmak için faydalıdır.
GetFieldNames(), belge sırasına göre ve yinelenenleri kaldırarak, tüm değer-tarzı birleştirme alanlarının adlarını döndürür.GetRegionNames(), belgede beyan edilen tümTableStartbölgelerinin adlarını döndürür.GetFields()her alanı,TableStart/TableEndişaretçileri dahil,MergeFieldnesneleri olarak döndürür.
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"]Her MergeField kendi Name, belgede saklandığı haliyle tam Instruction metni (örneğin MERGEFIELD FirstName \* MERGEFORMAT), sadece bölge işaretçileri için ayarlanan bir RegionName (örneğin "Orders", "TableStart:Orders"'dan) ve alanı Value (bir veri değeri ile değiştirilen metin), TableStart veya TableEnd (tekrarlayan bir bölgenin sınırları) veya NextRecord (aynı şablon gövdesi içinde bir sonraki veri kaydına ilerleyen bir NEXT alanı) olarak sınıflandıran bir Kind sunar.
Eşleşmemiş Alanları ve Null Değerlerini Nasıl Kontrol Edebilirim?
Birleştirme davranışı MailMerge.Options üzerinden yapılandırılır:
| Seçenek | Default | Davranış |
|---|---|---|
RemoveUnusedFields | true | Veri kaynağında eşleşen anahtarı olmayan birleştirme alanlarını kaldırır. Yerinde bırakmak için false olarak ayarlayın. |
RemoveUnusedRegions | true | Veri kaynağında eşleşen tablo bulunmayan TableStart/TableEnd bölgelerini kaldırır. |
NullValueReplacement | "" | Bir alan için veri kaynağı null değeri sağladığında ikame edilen metin. |
CaseInsensitiveFieldNames | true | Alan adları eşleştirilirken büyük/küçük harf göz ardı edilir, bu Microsoft Word davranışıdır. |
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")Bir veri kaynağı olmadan doğrudan değer değiştirme için, bir Word belgesindeki metni nasıl değiştireceğinizi görün.
Sıkça Sorulan Sorular
C#'ta IronWord kullanarak posta birleştirme nedir?
C#'ta IronWord ile posta birleştirme, Word şablonlarındaki MERGEFIELD yer tutucularını sözlüklerden, DataTable, DataRow veya DataSet nesnelerinden gelen verilerle doldurmanıza olanak tanır ve faturalar ve raporlar gibi kişiselleştirilmiş belgeler oluşturmanızı sağlar.
IronWord, Microsoft Office olmadan posta birleştirmeyi nasıl gerçekleştirir?
IronWord, Microsoft Office olmadan posta birleştirmeyi, Word şablonlarını yükleyip WordDocument.MailMerge giriş noktasını kullanarak yer tutucuları verilerle değiştirerek gerçekleştirir.
IronWord ile posta birleştirme için bir sözlük kullanabilir miyim?
Evet, IronWord, alan adlarını Execute yöntemindeki sözlük anahtarlarıyla eşleştirerek sözlük kullanarak posta birleştirmeyi sağlar.
IronWord kullanarak DataTable ile posta birleştirmeyi nasıl yapabilirim?
IronWord'de DataTable ile posta birleştirmeyi, DataTable'ı Execute yöntemine geçirerek gerçekleştirebilirsiniz; bu yöntem, şablondaki birleştirme alanlarıyla eşleşen sütun adlarını kullanır.
Posta birleştirmede yinelenen bölgeler nelerdir ve IronWord'de nasıl ele alınırlar?
Posta birleştirmede yinelenen bölgeler, veri satırlarına göre genişleyebilen bölümlerdir ve fatura satırları gibi öğeler için mükemmeldir. IronWord, bunları TableStart ve TableEnd işaretçilerini kullanarak ExecuteWithRegions yöntemi aracılığıyla ele alır.
IronWord kullanarak bir şablonun birleştirme alanlarını nasıl inceleyebilirim?
IronWord'ün GetFieldNames ve GetRegionNames yöntemlerini kullanarak bir şablondaki birleştirme alanlarını ve bölge adlarını inceleyebilir, böylece şablonları doğrulayabilir veya veri kaynaklarını dinamik olarak oluşturabilirsiniz.
IronWord, posta birleştirmede eşleşmeyen alanlar ve null değerlerle nasıl ilgilenir?
IronWord, MailMerge.Options'ta yer alan RemoveUnusedFields, RemoveUnusedRegions ve NullValueReplacement gibi seçenekler sunarak eşleşmeyen alanlar ve null değerler için davranışı kontrol etmenize olanak tanır.
IronWord kullanarak bir Word belgesini posta birleştirme için en minimal iş akışı nedir?
En minimal iş akışı, IronWord kütüphanesini indirmenizi, bir Word şablonu oluşturmanızı, WordDocument ile yüklemenizi, verilerinizle birleştirmeyi gerçekleştirmenizi ve doldurulmuş belgeyi kaydetmenizi içerir.
IronWord posta birleştirmede alan adı eşleşmesini büyük/küçük harf duyarlılığı nasıl etkiler?
IronWord'de, posta birleştirmede alan adı aramaları varsayılan olarak Microsoft Word'e benzer şekilde büyük/küçük harf duyarsızdır. Bu davranışı MailMerge.Options.CaseInsensitiveFieldNames kullanarak ayarlayabilirsiniz.
IronWord, birden fazla belge veya şablonla posta birleştirmeyi nasıl destekler?
IronWord, aynı şablonu farklı verilerle yeniden kullanarak veya tekrar eden veri girişleri için ExecuteWithRegions yöntemini kullanarak birden fazla belgeyi hızla doldurmanıza olanak tanır.
Curtis Chau, Bilgisayar Bilimleri alanında Lisans Derecesine (Carleton Üniversitesi) sahip ve Node.js, TypeScript, JavaScript ve React konularında uzmanlaşmış ön uç geliştirmeyle ilgileniyor. Sezgisel ve estetik açıdan hoş kullanıcı arayüzleri oluşturma tutkunu, Curtis modern çerçevelerle çalışmayı ve iyi yapılandırılmış, görsel olarak çekici kılavuzlar oluşturmayı seviyor.