Mailings: a CSV or Excel list, merge fields, address blocks, rules, envelopes, labels, preview, merge to a new document
Word's Mailings tab wraps the merge in four steps: pick a recipient list, insert merge fields into the letter, preview a recipient, and finish by merging every recipient into a new document. DocWright does each the way Word does, and never changes the letter.
A recipient list from CSV
using DocWright.MailMerge;
CsvMergeData list = CsvMergeData.Read(File.OpenText("recipients.csv")); // or delimiter: '\t'
foreach (string name in list.FieldNames) { Console.WriteLine(name); }
The first row names the fields. A value in double quotes keeps its commas and line breaks, and "" inside quotes is one
quote. Field names are Word's: a space becomes _, and any character that is not a letter, a digit or _ is dropped,
so a column "First Name" is the field First_Name. A file is refused (FormatException) when a quote is never closed,
a value is over 1 MB or a row has more than 255 fields.
A recipient list from an Excel workbook
using Stream book = File.OpenRead("recipients.xlsx");
IReadOnlyList<string> sheets = XlsxMergeData.SheetNames(book); // the workbook's sheets, in order
book.Position = 0;
XlsxMergeData list = XlsxMergeData.Read(book, sheet: "Recipients"); // null: the first sheet
A sheet's first row names the fields, named as for a CSV list. Every value is the text Word's merge shows, not the
cell's formatting: a number in full, up to 17 significant digits (1234.5, not $1,234.50; 0.1 is
0.10000000000000001, as Word merges it), a date as M/d/yyyy, a
Boolean as True / False, a text cell (007) exactly as typed. Empty rows are skipped. A workbook is refused
(InvalidDataException) when it is not a workbook, has more than 10,000 entries, a part over 64 MB, or the sheet named
is not there.
Address Block and Greeting Line
document.InsertAddressBlock(at); // ADDRESSBLOCK \f "<<_TITLE0_ >><<_FIRST0_>><< _LAST0_>>…" \l 1033 \c 2 \e "United States" \d
document.InsertGreetingLine(at); // GREETINGLINE \f "<<_BEFORE_ Dear >><<_TITLE0_ >><<_LAST0_>><<_AFTER_ ,>>" \l 1033 \e "Dear Sir or Madam,"
Both are written as Word's dialogs write them (the defaults are MergeFieldEditingExtensions.DefaultAddressBlockSwitches
and DefaultGreetingLineSwitches; pass your own switches for another format). At merge time each code is filled from
the list's address field: Word's names (First Name, Last Name, Address 1, City, Postal Code, Country or Region, …, see
AddressFields.All), matched to the list's columns by Word's synonyms (Surname is the last name, ZIP the postal
code) or by MailMergeOptions.AddressFieldMap, which is Word's Match Fields:
var options = new MailMergeOptions { AddressFieldMap = new Dictionary<string, string> { ["City"] = "Town" } };
IReadOnlyDictionary<string, string> matched = AddressFields.Match(list.FieldNames); // what Word matches on its own
The address block follows Word's rules: a group (<< _LAST0_>>) is left out when its field is empty, a blank line is
dropped, \c 2 adds the country unless it is the one named by \e, and the countries Word lays out its own way (the UK,
France, Germany, Canada, Australia, Japan) get that layout. Each line of the block is its own paragraph in the merged
document. The greeting line uses the title and last name when there are both, falls back to the full name, and to the
\e text when the record has no name.
Rules
using DocWright.Dom.Editing;
document.InsertIfThenElse(at, "City", MergeComparison.Equal, "London", "See you at the office.", "See you online.");
document.InsertSkipRecordIf(at, "Email", MergeComparison.IsBlank, "");
document.InsertNextRecordIf(at, "Region", MergeComparison.NotEqual, "EU");
document.InsertNextRecord(at);
document.InsertMergeRecordNumber(at); // MERGEREC
document.InsertMergeSequenceNumber(at); // MERGESEQ
These are Word's Rules menu. The compared field is written as Word writes it, a nested MERGEFIELD
(IF { MERGEFIELD City } = "London" "…" "…"), so the letter opens and merges in Word the same way. The field's value is
compared whole, as Word compares it: a city "New York, NY" is one operand, and an empty one is blank. A value or text
over 255 characters, or one holding a quotation mark, is refused (ArgumentException).
Labels
using DocWright.Dom.Editing;
// 30 labels of 2 5/8 x 1 in on Letter: top 0.5 in, side 3/16 in, 2 3/4 in across, 1 in down (twips).
var layout = new LabelLayout(12240, 15840, topMargin: 720, sideMargin: 270, width: 3780, height: 1440,
horizontalPitch: 3960, verticalPitch: 1440, across: 3, down: 10);
using WordDocument sheet = LabelSheet.Create(layout, new[] { "Ada Lovelace", "12 St James Square" }); // one address
using WordDocument labels = LabelSheet.Create(layout); // a merge sheet
labels.InsertAddressBlock(DocumentPosition.StartOf(firstLabel));
labels.UpdateLabels(); // Word's Update Labels
LabelSheet.Create builds the sheet Word's Labels and Start Mail Merge > Labels build for a label's geometry.
The numbers are the label product's; DocWright ships no catalog of products. The sheet is one section whose margins put
the first label in place, holding a borderless fixed table: a column per label, and a spacer column between two labels
when the gap is at least 0.1 in (a smaller gap is folded into the label, as its cell margins); rows the same way down,
each exactly the label's height. Every paragraph is indented by half the label's width in points, at most 144 twips.
A merge sheet's labels after the first start with «Next Record» (a NEXT field). Put the fields in the first label
and UpdateLabels copies it into the others, after their NEXT, as one undoable edit. Merged, each label takes the
next record and labels past the end of the list are blank, as in Word.
Envelopes
using DocWright.Dom.Editing;
using WordDocument envelope = EnvelopeDocument.Create(EnvelopeLayout.Named("DL"),
delivery: new[] { "Ada Lovelace", "12 St James Square", "London SW1Y 4JH" },
returnAddress: new[] { "Grace Hopper", "1 Navy Way" });
using WordDocument merge = EnvelopeDocument.Create(EnvelopeLayout.Named("Size 10")); // an empty delivery address for the fields
EnvelopeDocument.Create builds the envelope Word's Envelopes and Start Mail Merge > Envelopes build: one
landscape section of the envelope's size (EnvelopeLayout.Sizes lists Word's fifteen, with Word's own page sizes), the
addresses in Word's Envelope Address and Envelope Return styles. Their text frames place them:
the delivery address centred at the bottom, the return address at the margin's top left, or where EnvelopeLayout's
positions say (Envelope Options' From left and From top).
Add to Document puts the envelope into the letter instead, as its first section, before the first paragraph wherever the caret is; a document that already starts with an envelope has it replaced (Word's Change Document). Each is one undoable edit:
DocumentEdit edit = letter.AddEnvelope(caret, EnvelopeLayout.Named("Size 10"),
delivery: new[] { "Ada Lovelace", "12 St James Square" }, returnAddress: new[] { "Grace Hopper", "1 Navy Way" });
bool change = letter.StartsWithEnvelope(); // true now: a second AddEnvelope replaces this one
edit.Undo();
Merge fields
using DocWright.Dom.Editing;
document.InsertMergeField(DocumentPosition.StartOf(paragraph), "First_Name");
The field is written as Word's Insert Merge Field writes it: MERGEFIELD First_Name, showing «First_Name» until
the letter is merged. It is one undoable edit.
Preview and merge
using WordDocument preview = letter.PreviewRecord(list.Records[0]); // one recipient
using WordDocument third = letter.PreviewRecord(list.Records[2], recordNumber: 3); // «Merge Record #» shows 3
(WordDocument merged, MergeResult result) = letter.MergeToNewDocument(list.CreateReader()); // everyone
MergeToNewDocument is Word's Edit Individual Documents: a copy of the letter per recipient, each in its own
section on a new page, every merge field replaced by its value, and none of the letter's own mail-merge settings. The
letter is not changed by either call. NEXT, IF and SKIPIF work as they do in the merge itself.