Mail Merge With JSON
Mail merge fills a reusable workbook template from a JSON record. Fixed bindings write single values, such as the customer name and other header fields, into their cells. Repeat blocks expand a band of template rows for each element of an array, such as the lines of an invoice, and formula cells calculate the totals after the expansion.
You can merge in the browser editor, or without a browser with the .NET and Node.js server packages. The examples below merge an invoice for the customer Alpine Design with two line items; the server examples load the invoice template of the Sample Documents.
Inspect a Field in the Template
The invoice template binds the customer cell to the input JSON and repeats one row for each invoice item:

Select the customer-name field, then choose Reporting → Field Properties:

The field path identifies the value in the input JSON, and the field type describes the value to write. In this invoice, customer.name fills the selected customer cell. The repeating item block handles the description, quantity and unit price separately, while worksheet formulas calculate the amounts and totals.
Define and Merge a Template in the Browser
The following code defines the bindings of an invoice on the first worksheet, captures a template and merges a record into it. editor is the Spreadsheet of the browser editor, created as in JavaScript:
const book = editor.workbook;
const sheet = book.sheets.at(0);
sheet.cell('D8').setFormula('=B8*C8');
book.setMailMerge({
version: 1,
bindings: [{ sheetId: sheet.id, cell: 'B2', path: 'customer.name', type: 'string' }],
repeatBlocks: [{
id: 'items', sheetId: sheet.id, source: 'items', templateRange: 'A8:D8',
fields: [
{ cell: 'A8', path: 'description', type: 'string' },
{ cell: 'B8', path: 'quantity', type: 'number' },
{ cell: 'C8', path: 'unitPrice', type: 'number' }
]
}]
});
const template = book.createMailMergeTemplate();
const result = await template.merge({
customer: { name: 'Alpine Design' },
items: [
{ description: 'Consulting', quantity: 3, unitPrice: 120 },
{ description: 'Training', quantity: 2, unitPrice: 90 }
]
});
// The independent result workbook has no browser font host.
// Load it into an initialized editor for PDF output with that editor's fonts.
const mergedBytes = await result.workbook.save(StreamType.InternalWorkbookFormat);
await editor.load(mergedBytes, StreamType.InternalWorkbookFormat);
const output = await editor.save(StreamType.PDF);
The code works as follows:
- Workbook.sheets and SheetCollection.at return the first worksheet. Worksheet.cell and Cell.setFormula put the formula
=B8*C8intoD8, the amount of the template row. - Workbook.setMailMerge stores the merge definition. Its binding writes
customer.nameintoB2as astring. Its repeat blockitemsrepeats the template rangeA8:D8for each element of theitemsarray and writesdescription,quantityandunitPriceintoA8,B8andC8. Worksheet.id identifies the worksheet of the binding and the block. - Workbook.createMailMergeTemplate captures a reusable template, a MailMergeTemplate.
- MailMergeTemplate.merge merges the record and returns an independent workbook and diagnostics.
- The independent result workbook has no browser font host. Workbook.save saves it in the TXWB format,
StreamType.InternalWorkbookFormatof the StreamType enumeration. Spreadsheet.load loads it into the initialized editor, and Spreadsheet.save creates the PDF with that editor's fonts.
createMailMergeTemplate() captures a reusable template, and every repeated merge should start from this captured original, not from a result that is already expanded. For an in-place workflow, book.merge() (Workbook.merge) is available.
Design a Template in the Reporting UI
In the editor, you build the bindings with the commands of the Reporting tab, described in Ribbon and Contextual Commands:
- Load authoring data through
editor.ui.loadMergeData(record). - Select a cell or a band of rows.
- Insert a field or a block with the Reporting commands.
Inside repeat blocks, choose relative item paths, such as description in the example above. The authoring source data is application configuration, not serialized executable code. Spreadsheet.ui returns the editor UI, and loadMergeData loads the application's data source without putting transient data into the workbook JSON.
Merge in Node.js
On a Node.js server, install only @txtextcontrol/tx-sheet-control-server and put the downloaded invoice template, invoice-template.txwb, beside the application. Supply a validated application record with the shape shown above: a customer with a name and an items array.
import { readFile, writeFile } from 'node:fs/promises';
import { ServerSheetControl, StreamType } from '@txtextcontrol/tx-sheet-control-server';
const control = new ServerSheetControl();
try {
await control.load(new Uint8Array(await readFile('invoice-template.txwb')),
StreamType.InternalWorkbookFormat);
const diagnostics = await control.workbook.merge({
customer: { name: 'Alpine Design' },
items: [
{ description: 'Consulting', quantity: 3, unitPrice: 120 },
{ description: 'Training', quantity: 2, unitPrice: 90 }
]
});
if (diagnostics.formulaErrors.length) throw new Error('The invoice contains formula errors.');
console.log(diagnostics.warnings);
await writeFile('invoice.pdf', await control.save(StreamType.PDF));
} finally {
control.destroy();
}
The code works as follows:
- ServerSheetControl is an isolated workbook without an editor or DOM. ServerSheetControl.load loads the bytes of
invoice-template.txwbasStreamType.InternalWorkbookFormatof the Node.js StreamType. - ServerSheetControl.workbook returns the workbook, and Workbook.merge merges the record into it and returns the diagnostics. The code throws an error if
formulaErrorsis not empty and logs thewarnings. - ServerSheetControl.save returns the PDF bytes for
StreamType.PDF, whichwriteFilestores asinvoice.pdf. - ServerSheetControl.destroy in the
finallyblock disposes the isolated document.
Merge in .NET
The independent Server NuGet package, TXTextControl.TXSheetControl.Server, can perform the same pipeline in .NET. Download the sample TXWB and put a validated record into invoice-data.json. Save a TXWB template, load it with ServerSheetControl, then await control.Workbook.MergeAsync(record) and export the result through SaveAsync:
using System.Text.Json;
using TXTextControl.TXSheetControl.Server;
using var data = JsonDocument.Parse(await File.ReadAllTextAsync("invoice-data.json"));
await using var control = new ServerSheetControl();
await control.LoadAsync("invoice-template.txwb", StreamType.InternalWorkbookFormat);
var diagnostics = await control.Workbook.MergeAsync(data.RootElement);
if (diagnostics.GetProperty("formulaErrors").GetArrayLength() != 0)
{
throw new InvalidOperationException("The invoice contains formula errors.");
}
Console.WriteLine(diagnostics.GetProperty("warnings"));
await control.SaveAsync("invoice.pdf", StreamType.PDF);
The code works as follows:
JsonDocument.Parsereads the record frominvoice-data.json.- ServerSheetControl owns an independent spreadsheet document.
await usingreleases it with DisposeAsync at the end of the scope. - LoadAsync loads
invoice-template.txwbasStreamType.InternalWorkbookFormatof the .NET StreamType. - Workbook.MergeAsync, reached through ServerSheetControl.Workbook, merges
data.RootElementand returns the diagnostics as aJsonElement. The code throws anInvalidOperationExceptionifformulaErrorsis not empty and writes thewarningsto the console. - SaveAsync saves the result as
invoice.pdfwithStreamType.PDF.
No browser is needed for server merging. Reload the template before you process another, unrelated record.
Important
Check Before Delivery. Review the warnings, the repeated ranges and the formula errors before you deliver a report.
Next Steps
- Merge Policies and Template Design: choose binding paths, types and missing-data policies, and design repeat bands.
- Invoice Report Pipeline: follow the invoice from template and data to a delivered PDF.
- Exporting Worksheets to PDF: set the PDF options of the merged report.
- Loading and Saving Workbooks: persist templates in TXWB and load and save their bytes.
- Mail Merge: fix blank fields, duplicate rows and wrong totals.