Products Technologies Demo Docs Blog Support Company

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

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, 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 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). 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
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
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, repeating block design, and PDF export. To create Excel layouts from scratch, see How to Create an Excel XLSX File in C# .NET.

Download trial

Frequently Asked Questions

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.

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

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

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

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

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.

Stay in the loop!

Subscribe to the newsletter to receive the latest updates.

TX Sheet Control

Excel-compatible spreadsheet editing, a robust calculation engine, and interactive dashboards for business applications.

Learn more about TX Sheet Control

Related Posts

C#Document GenerationExcel

How to Create an Excel XLSX File in C# .NET

Learn how to create an Excel XLSX file from scratch in C# .NET with TX Sheet Control. This step-by-step tutorial creates a sales workbook, writes text and numbers, adds formulas, applies currency…


ReportingMailMerge.NET

Server-Side Spreadsheet Processing and Reporting with TX Sheet Control in…

Learn how TX Sheet Control creates, merges, and exports workbooks in .NET and Node.js without a browser. This article covers mail merge with visually designed templates, typed bindings and…


C#Linux.NET

Check TX Text Control Template Dependencies Before Deployment

When templates are moved from Windows to Linux, from TX Text Control Classic to Core, or from one server to another, missing fonts, images, merge fields, blocks, and form field names can break…


ReportingWindows FormsExcel

Merge Excel Documents into MailMerge Templates using IncludeText Fields

IncludeText fields in TX Text Control templates reference external Excel files during mail merge. The process loads .xlsx files as temporary ServerTextControl instances, using Bookmark to target…

Share this blog post on:

​​​