# How to Generate PDF Reports from Excel Templates in C#

> Generate PDF reports from Excel templates using the mail merge feature of TX Sheet Control. Define a repeating row block, merge a JSON array, expand formulas and totals, and export the completed report from C#.

- **Author:** Bjoern Meyer
- **Published:** 2026-12-04
- **Modified:** 2026-12-03
- **Description:** Generate PDF reports from Excel templates using the mail merge feature of TX Sheet Control. Define a repeating row block, merge a JSON array, expand formulas and totals, and export the completed report from C#.
- **9 min read** (1604 words)
- **Tags:**
  - PDF
  - XLSX
  - Excel
  - C#
  - .NET
  - Reporting
  - Templates
  - Mail Merge
- **Web URL:** https://www.textcontrol.com/blog/2026/12/04/how-to-generate-pdf-reports-from-excel-templates-in-csharp/
- **LLMs URL:** https://www.textcontrol.com/blog/2026/12/04/how-to-generate-pdf-reports-from-excel-templates-in-csharp/llms.txt
- **LLMs-Full URL:** https://www.textcontrol.com/blog/2026/12/04/how-to-generate-pdf-reports-from-excel-templates-in-csharp/llms-full.txt

---

Generate PDF reports from Excel templates using the **mail merge** feature of **TX Sheet Control**. Define a repeating row block, supply an array of records, and let the merge create the detail rows and adjust their formulas.

This example uses **TX Sheet Control 2.0.0** and **.NET 10**. An Excel template provides the report design and one service row. Merging four service records produces a monthly sales report with a total of **$1,300.00**.

### Create the C# Application

Install the .NET 10 SDK and configure the [Text Control NuGet feed](https://docs.textcontrol.com/tx-sheet-control/installation/nuget/) or use the NuGet folder from the product download. Create a console project and add the Server package:

```
dotnet new console -n TXSheetControl.ExcelTemplatePdf -f net10.0
cd TXSheetControl.ExcelTemplatePdf
dotnet add package TXTextControl.TXSheetControl.Server --version 2.0.0
```

### Prepare a Template with One Detail Row

[Download the template, JSON data, and example PDF (ZIP)](https://s1-www.textcontrol.com/assets/dist/blog/2026/12/04/a/assets/excel-template-report.zip). Extract `sales-report-template.xlsx` and `report-data.json` into the project directory.

The XLSX file stores the layout, formatting, and formulas. Row 8 is the prototype service row; the total is in row 10. The C# definition below connects these cells to the merge data:

| Cell or range | Merge field or formula |
|---|---|
| `A5` | Reporting period: `period` |
| `C5` | Client: `customer.name` |
| `A8:D8` | Repeating block for the `items` array |
| `A8`, `B8`, `C8` | Item fields: `description`, `quantity`, `unitPrice` |
| `D8` | Line amount: `=B8*C8` |
| `D10` | Grand total: `=SUM(D8:D8)` |

![Excel template with mail merge fields and a single repeating items block in A8:D8](https://s1-www.textcontrol.com/assets/dist/blog/2026/12/04/a/assets/excel-report-template.webp "Excel template with mail merge fields and a single repeating items block in A8:D8") The template after applying the merge definition. The highlighted row repeats for each item.

### Load the Excel Template

Place your signed license in `tx-sheet-control.license` in the project directory. Load the XLSX layout and obtain its first worksheet:

```
using System.Text.Json;
using TXTextControl.TXSheetControl.Server;

string templatePath = args.Length > 0 ? args[0] : "sales-report-template.xlsx";
string dataPath = args.Length > 1 ? args[1] : "report-data.json";
string outputPath = Path.GetFullPath(args.Length > 2 ? args[2] : "sales-report.pdf");
string license = await File.ReadAllTextAsync(
    Environment.GetEnvironmentVariable("TX_SHEET_LICENSE_PATH")
        ?? "tx-sheet-control.license");

await using var control = new ServerSheetControl(new ServerSheetControlOptions
{
    License = license,
    Locale = "en-US",
    Currency = "USD"
});
await control.LoadAsync(templatePath, StreamType.SpreadsheetML);

var workbook = control.Workbook;
var sheet = await workbook.Sheets.AtAsync(0);
```

### Define the Merge Fields and Repeating Block

`SetMailMergeAsync` defines two header bindings and a repeating block named `services`. Its `source` points to the `items` array, and `templateRange` selects A8:D8:

```
await workbook.SetMailMergeAsync(new
{
    version = 1,
    bindings = new[]
    {
        new { sheetId = sheet.Id, cell = "A5", path = "period", type = "string" },
        new { sheetId = sheet.Id, cell = "C5", path = "customer.name", type = "string" }
    },
    repeatBlocks = new[]
    {
        new
        {
            id = "services",
            sheetId = sheet.Id,
            source = "items",
            templateRange = "A8:D8",
            fields = new[]
            {
                new { cell = "A8", path = "description", type = "string" },
                new { cell = "B8", path = "quantity", type = "number" },
                new { cell = "C8", path = "unitPrice", type = "number" }
            }
        }
    }
});

var template = await workbook.CreateMailMergeTemplateAsync();
```

The item field paths are relative to each array element. Each repeated row receives its description, quantity, and unit price. D8 remains a worksheet formula, so `=B8*C8` adjusts to `=B9*C9` in the next row.

`CreateMailMergeTemplateAsync` captures a reusable template. Each merge creates an independent report from that original.

### Supply the Report Data

Save the following record as `report-data.json`. The `items` array determines the number of service rows:

```
{
  "period": "November 2026",
  "customer": {
    "name": "Alpine Retail"
  },
  "items": [
    {
      "description": "Consulting",
      "quantity": 4,
      "unitPrice": 125
    },
    {
      "description": "Training",
      "quantity": 2,
      "unitPrice": 175
    },
    {
      "description": "Support",
      "quantity": 6,
      "unitPrice": 45
    },
    {
      "description": "Hosting",
      "quantity": 12,
      "unitPrice": 15
    }
  ]
}
```

### Merge the Repeating Rows

Read the JSON record and pass it to `template.MergeAsync`. The result contains the merged workbook and diagnostics:

```
using var data = JsonDocument.Parse(await File.ReadAllTextAsync(dataPath));
int itemCount = data.RootElement.GetProperty("items").GetArrayLength();
await using var merged = await template.MergeAsync(data.RootElement);

if (merged.Metadata.GetProperty("formulaErrors").GetArrayLength() != 0)
{
    throw new InvalidOperationException("The merged report contains formula errors.");
}

var reportSheet = await merged.Workbook.Sheets.AtAsync(0);
int totalRow = 9 + itemCount;
int lastPrintRow = 13 + itemCount;
decimal total = (await reportSheet.Cell($"D{totalRow}").GetValueAsync()).GetDecimal();
```

With four items, the merge expands row 8 into rows 8-11 and moves the total from D10 to D13. The total formula becomes `=SUM(D8:D11)` and calculates to **$1,300.00**. Row formatting and height are copied with the block.

The code checks `formulaErrors` before exporting and obtains a worksheet handle from the merged report. `await using` disposes that report before its owner control.

### Configure the Report Pages

The total starts at row 10 in the template. After expansion, its row is `9 + itemCount`. The print area ends at `13 + itemCount` to include the notes below the total:

```
await reportSheet.Print.ConfigureAsync(new
{
    page = new { size = "A4", orientation = "portrait" },
    margins = new { unit = "mm", left = 18, right = 18, top = 18, bottom = 18 },
    area = $"A1:D{lastPrintRow}",
    gridlines = false,
    fitToPage = true,
    fitToWidth = 1,
    fitToHeight = 0,
    footer = new { left = "Northwind Services", right = "Page &P of &N" }
});
```

The report uses A4 portrait paper and 18 mm margins. `fitToWidth = 1` keeps the columns on one page, while `fitToHeight = 0` allows additional pages as the item list grows. The footer fields `&P` and `&N` insert the page number and page count.

### Export the Merged Report to PDF

Save through `merged.Control` with `StreamType.PDF`. `PdfOptions.Sheet` selects the worksheet in the merged report:

```
Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!);
await merged.Control.SaveAsync(outputPath, StreamType.PDF, new SaveOptions
{
    Pdf = new PdfOptions
    {
        Sheet = reportSheet,
        Locale = "en-US",
        TimeZone = "UTC",
        Title = "Monthly Sales Report"
    }
});

Console.WriteLine($"Created: {outputPath}");
Console.WriteLine($"Items: {itemCount}");
Console.WriteLine($"Grand total: {total:0.00}");
```

![Mail merged A4 sales PDF for Alpine Retail with four repeated service rows and a $1,300.00 grand total](https://s1-www.textcontrol.com/assets/dist/blog/2026/12/04/a/assets/generated-pdf-report.webp "Mail merged A4 sales PDF for Alpine Retail with four repeated service rows and a $1,300.00 grand total") One template row becomes four service rows, followed by the calculated grand total.

### Run the Complete Example

Replace `Program.cs` with the complete example below:

```
using System.Text.Json;
using TXTextControl.TXSheetControl.Server;

// 1. Load the Excel template.
string templatePath = args.Length > 0 ? args[0] : "sales-report-template.xlsx";
string dataPath = args.Length > 1 ? args[1] : "report-data.json";
string outputPath = Path.GetFullPath(args.Length > 2 ? args[2] : "sales-report.pdf");
string license = await File.ReadAllTextAsync(
    Environment.GetEnvironmentVariable("TX_SHEET_LICENSE_PATH")
        ?? "tx-sheet-control.license");

await using var control = new ServerSheetControl(new ServerSheetControlOptions
{
    License = license,
    Locale = "en-US",
    Currency = "USD"
});
await control.LoadAsync(templatePath, StreamType.SpreadsheetML);

var workbook = control.Workbook;
var sheet = await workbook.Sheets.AtAsync(0);

// 2. Define the fields and repeating row block.
await workbook.SetMailMergeAsync(new
{
    version = 1,
    bindings = new[]
    {
        new { sheetId = sheet.Id, cell = "A5", path = "period", type = "string" },
        new { sheetId = sheet.Id, cell = "C5", path = "customer.name", type = "string" }
    },
    repeatBlocks = new[]
    {
        new
        {
            id = "services",
            sheetId = sheet.Id,
            source = "items",
            templateRange = "A8:D8",
            fields = new[]
            {
                new { cell = "A8", path = "description", type = "string" },
                new { cell = "B8", path = "quantity", type = "number" },
                new { cell = "C8", path = "unitPrice", type = "number" }
            }
        }
    }
});

var template = await workbook.CreateMailMergeTemplateAsync();

// 3. Merge the application data.
using var data = JsonDocument.Parse(await File.ReadAllTextAsync(dataPath));
int itemCount = data.RootElement.GetProperty("items").GetArrayLength();
await using var merged = await template.MergeAsync(data.RootElement);

if (merged.Metadata.GetProperty("formulaErrors").GetArrayLength() != 0)
{
    throw new InvalidOperationException("The merged report contains formula errors.");
}

var reportSheet = await merged.Workbook.Sheets.AtAsync(0);
int totalRow = 9 + itemCount;
int lastPrintRow = 13 + itemCount;
decimal total = (await reportSheet.Cell($"D{totalRow}").GetValueAsync()).GetDecimal();

// 4. Configure the printed page.
await reportSheet.Print.ConfigureAsync(new
{
    page = new { size = "A4", orientation = "portrait" },
    margins = new { unit = "mm", left = 18, right = 18, top = 18, bottom = 18 },
    area = $"A1:D{lastPrintRow}",
    gridlines = false,
    fitToPage = true,
    fitToWidth = 1,
    fitToHeight = 0,
    footer = new { left = "Northwind Services", right = "Page &P of &N" }
});

// 5. Export the merged report to PDF.
Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!);
await merged.Control.SaveAsync(outputPath, StreamType.PDF, new SaveOptions
{
    Pdf = new PdfOptions
    {
        Sheet = reportSheet,
        Locale = "en-US",
        TimeZone = "UTC",
        Title = "Monthly Sales Report"
    }
});

Console.WriteLine($"Created: {outputPath}");
Console.WriteLine($"Items: {itemCount}");
Console.WriteLine($"Grand total: {total:0.00}");
```

```
dotnet run -- sales-report-template.xlsx report-data.json sales-report.pdf
```

The application creates `sales-report.pdf` and reports **4 items** and a grand total of **1300.00**. Add or remove records in the JSON array to generate a report with a different number of rows.

The template uses the supplied Liberation Sans font. Deploy the complete application publish output so the font files remain available for PDF rendering.

Read more about [mail merge](https://docs.textcontrol.com/tx-sheet-control/mail-merge/), [repeating block design](https://docs.textcontrol.com/tx-sheet-control/mail-merge/template-design/), and [PDF export](https://docs.textcontrol.com/tx-sheet-control/pdf/export/). To create Excel layouts from scratch, see [How to Create an Excel XLSX File in C# .NET](https://www.textcontrol.com/blog/2026/12/03/how-to-create-an-excel-xlsx-file-in-csharp-dotnet/llms-full.txt).

[Download trial](https://www.textcontrol.com/product/tx-sheet-control/download/trial/ "Download Trial")

### Frequently Asked Questions

How does the repeating row block work? 
---------------------------------------

The services block repeats A8:D8 for each record in the items array. Its fields write the description, quantity, and unit price into each generated row.

Do the formulas expand with the rows? 
--------------------------------------

Yes. The line formula adjusts for each repeated row, and the total below the block moves and expands to include the generated amounts.

How many detail rows does the template need? 
---------------------------------------------

The template contains one prototype row. The length of the items array determines the number of rows in the merged report.

Where are the merge bindings defined? 
--------------------------------------

This example loads the XLSX layout and defines its bindings with SetMailMergeAsync in C#. Use TXWB when saving template bindings inside the workbook file.

Can I reuse the template for another report? 
---------------------------------------------

Yes. CreateMailMergeTemplateAsync captures the original template. Each MergeAsync call returns an independent result that should be disposed after export.

Will a long report continue onto additional PDF pages? 
-------------------------------------------------------

Yes. The print area follows the expanded data, and fitToHeight is set to 0 so the report can grow vertically while staying one page wide.

---

## About Bjoern Meyer

As CEO, Bjoern is the visionary behind our strategic direction and business development, bridging the gap between our customers and engineering teams. His deep passion for coding and web technologies drives the creation of innovative products. If you're at a tech conference, be sure to stop by our booth - you'll most likely meet Bjoern in person. With an advanced graduate degree (Dipl. Inf.) in Computer Science, specializing in AI, from the University of Bremen, Bjoern brings significant expertise to his role. In his spare time, Bjoern enjoys running, paragliding, mountain biking, and playing the piano.

- [LinkedIn](https://www.linkedin.com/in/bjoernmeyer/)
- [X](https://x.com/txbjoern)
- [GitHub](https://github.com/bjoerntx)

---

## Related Posts

- [How to Create an Excel XLSX File in C# .NET](https://www.textcontrol.com/blog/2026/12/03/how-to-create-an-excel-xlsx-file-in-csharp-dotnet/llms.txt)
- [Server-Side Spreadsheet Processing and Reporting with TX Sheet Control in .NET and Node.js](https://www.textcontrol.com/blog/2026/12/01/server-side-spreadsheet-processing-and-reporting-with-tx-sheet-control/llms.txt)
- [Check TX Text Control Template Dependencies Before Deployment](https://www.textcontrol.com/blog/2026/07/28/check-tx-text-control-template-dependencies-before-deployment/llms.txt)
- [Merge Excel Documents into MailMerge Templates using IncludeText Fields](https://www.textcontrol.com/blog/2019/08/13/merge-excel-documents-into-mailmerge-templates/llms.txt)
