# Mail Merge With JSON

> Merge JSON records into workbook templates with bindings and repeat blocks in the browser, Node.js or .NET, check the diagnostics and export the invoice as PDF.

- **Product:** TX Sheet Control
- **Section:** Documentation
- **Kind:** Topic
- **Path:** TX Sheet Control > Mail Merge > Mail Merge With JSON
- **3650 words**
- **Web URL:** https://docs.textcontrol.com/tx-sheet-control/mail-merge/overview/
- **LLMs URL:** https://docs.textcontrol.com/tx-sheet-control/mail-merge/overview/llms.txt
- **LLMs-Full URL:** https://docs.textcontrol.com/tx-sheet-control/mail-merge/overview/llms-full.txt

---

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](https://docs.textcontrol.com/tx-sheet-control/overview/sample-documents/llms-full.txt).

### 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:

![Invoice template with the Reporting ribbon and merge bindings: the customer name in cell B3 and the line-item row below the column headings](https://docs.textcontrol.com/assets/img/tx-sheet-control/mail-merge-template.fa0e3a55.webp)

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

![Merge Field Properties dialog binding the selected invoice cell to customer.name, with the cell B3, the field path customer.name and the data type Text](https://docs.textcontrol.com/assets/img/tx-sheet-control/mail-merge-field-dialog.737bc02e.webp)

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](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/spreadsheet/llms-full.txt) of the browser editor, created as in [JavaScript](https://docs.textcontrol.com/tx-sheet-control/getting-started/spreadsheet-editor/javascript/llms-full.txt):

```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](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/workbook/sheets-property/llms-full.txt) and [SheetCollection.at](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/sheetcollection/at-method/llms-full.txt) return the first worksheet. [Worksheet.cell](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/worksheet/cell-method/llms-full.txt) and [Cell.setFormula](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/cell/setformula-method/llms-full.txt) put the formula `=B8*C8` into `D8`, the amount of the template row.
- [Workbook.setMailMerge](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/workbook/setmailmerge-method/llms-full.txt) stores the merge definition. Its binding writes `customer.name` into `B2` as a `string`. Its repeat block `items` repeats the template range `A8:D8` for each element of the `items` array and writes `description`, `quantity` and `unitPrice` into `A8`, `B8` and `C8`. [Worksheet.id](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/worksheet/id-property/llms-full.txt) identifies the worksheet of the binding and the block.
- [Workbook.createMailMergeTemplate](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/workbook/createmailmergetemplate-method/llms-full.txt) captures a reusable template, a [MailMergeTemplate](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/mailmergetemplate/llms-full.txt).
- [MailMergeTemplate.merge](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/mailmergetemplate/merge-method/llms-full.txt) merges the record and returns an independent workbook and diagnostics.
- The independent result workbook has no browser font host. [Workbook.save](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/workbook/save-method/llms-full.txt) saves it in the TXWB format, `StreamType.InternalWorkbookFormat` of the [StreamType](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/streamtype/llms-full.txt) enumeration. [Spreadsheet.load](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/spreadsheet/load-method/llms-full.txt) loads it into the initialized editor, and [Spreadsheet.save](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/spreadsheet/save-method/llms-full.txt) 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](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/workbook/merge-method/llms-full.txt)) 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](https://docs.textcontrol.com/tx-sheet-control/spreadsheet-editor/ribbon/llms-full.txt):

1. Load authoring data through `editor.ui.loadMergeData(record)`.
2. Select a cell or a band of rows.
3. 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](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/browser/spreadsheet/ui-property/llms-full.txt) returns the editor UI, and [loadMergeData](https://docs.textcontrol.com/tx-sheet-control/reference/typescript-api/browser/editorui/loadmergedata-method/llms-full.txt) 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.

```javascript
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](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/nodejs/serversheetcontrol/llms-full.txt) is an isolated workbook without an editor or DOM. [ServerSheetControl.load](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/nodejs/serversheetcontrol/load-method/llms-full.txt) loads the bytes of `invoice-template.txwb` as `StreamType.InternalWorkbookFormat` of the Node.js [StreamType](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/nodejs/streamtype/llms-full.txt).
- [ServerSheetControl.workbook](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/nodejs/serversheetcontrol/workbook-property/llms-full.txt) returns the workbook, and [Workbook.merge](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/nodejs/workbook/merge-method/llms-full.txt) merges the record into it and returns the diagnostics. The code throws an error if `formulaErrors` is not empty and logs the `warnings`.
- [ServerSheetControl.save](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/nodejs/serversheetcontrol/save-method/llms-full.txt) returns the PDF bytes for `StreamType.PDF`, which `writeFile` stores as `invoice.pdf`.
- [ServerSheetControl.destroy](https://docs.textcontrol.com/tx-sheet-control/reference/javascript-api/nodejs/serversheetcontrol/destroy-method/llms-full.txt) in the `finally` block 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`:

```csharp
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.Parse` reads the record from `invoice-data.json`.
- [ServerSheetControl](https://docs.textcontrol.com/tx-sheet-control/reference/dotnet-api/txtextcontrol-txsheetcontrol-server/serversheetcontrol/llms-full.txt) owns an independent spreadsheet document. `await using` releases it with [DisposeAsync](https://docs.textcontrol.com/tx-sheet-control/reference/dotnet-api/txtextcontrol-txsheetcontrol-server/serversheetcontrol/disposeasync-method/llms-full.txt) at the end of the scope.
- [LoadAsync](https://docs.textcontrol.com/tx-sheet-control/reference/dotnet-api/txtextcontrol-txsheetcontrol-server/serversheetcontrol/loadasync-method/llms-full.txt) loads `invoice-template.txwb` as `StreamType.InternalWorkbookFormat` of the .NET [StreamType](https://docs.textcontrol.com/tx-sheet-control/reference/dotnet-api/txtextcontrol-txsheetcontrol-server/streamtype/llms-full.txt).
- [Workbook.MergeAsync](https://docs.textcontrol.com/tx-sheet-control/reference/dotnet-api/txtextcontrol-txsheetcontrol-server/workbook/mergeasync-method/llms-full.txt), reached through [ServerSheetControl.Workbook](https://docs.textcontrol.com/tx-sheet-control/reference/dotnet-api/txtextcontrol-txsheetcontrol-server/serversheetcontrol/workbook-property/llms-full.txt), merges `data.RootElement` and returns the diagnostics as a `JsonElement`. The code throws an `InvalidOperationException` if `formulaErrors` is not empty and writes the `warnings` to the console.
- [SaveAsync](https://docs.textcontrol.com/tx-sheet-control/reference/dotnet-api/txtextcontrol-txsheetcontrol-server/serversheetcontrol/saveasync-method/llms-full.txt) saves the result as `invoice.pdf` with `StreamType.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](https://docs.textcontrol.com/tx-sheet-control/mail-merge/template-design/llms-full.txt): choose binding paths, types and missing-data policies, and design repeat bands.
- [Invoice Report Pipeline](https://docs.textcontrol.com/tx-sheet-control/mail-merge/report-pipeline/llms-full.txt): follow the invoice from template and data to a delivered PDF.
- [Exporting Worksheets to PDF](https://docs.textcontrol.com/tx-sheet-control/pdf/export/llms-full.txt): set the PDF options of the merged report.
- [Loading and Saving Workbooks](https://docs.textcontrol.com/tx-sheet-control/document-processing/load-save/llms-full.txt): persist templates in TXWB and load and save their bytes.
- [Mail Merge](https://docs.textcontrol.com/tx-sheet-control/troubleshooting/mail-merge/llms-full.txt): fix blank fields, duplicate rows and wrong totals.

---

## Nearby

- **Previous:** [Mail Merge](https://docs.textcontrol.com/tx-sheet-control/mail-merge/llms-full.txt)
- **Next:** [Merge Policies and Template Design](https://docs.textcontrol.com/tx-sheet-control/mail-merge/template-design/llms-full.txt)
