Products Technologies Demo Docs Blog Support Company

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 formatting, and exports a complete Excel file without Microsoft Excel.

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

Creating an Excel XLSX file in C# is a common requirement for sales reports, invoices, and data exports. With TX Sheet Control, you can create a workbook, populate cells, calculate formulas, and save a formatted Excel document directly from a .NET application.

This tutorial builds a monthly sales report from scratch using TX Sheet Control 2.0.0 and a .NET 10 console application. The server package processes the workbook independently of the browser editor and does not require Microsoft Excel to be installed. The result is a sales-report.xlsx file with four service lines, editable formulas, currency formatting, and a grand total of $945.00.

Create the .NET Project and Install the NuGet Package

Install the .NET 10 SDK or use Visual Studio 2026. Configure the Text Control Private NuGet Feed with the supplied NuGet configuration. Alternatively, use the nuget folder from the TX Sheet Control download as a local package source.

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

Use the TXTextControl.TXSheetControl.Server namespace for the control, workbook types, and file formats in this example. The NuGet package supplies the processing engine and its required assets.

1. Create a Workbook and Configure the License

Place your signed license file, tx-sheet-control.license, in the project directory. Keep it outside source control. The following code reads it from the current working directory, or from the file path specified by the optional TX_SHEET_LICENSE_PATH environment variable.

using TXTextControl.TXSheetControl.Server;

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,
    SheetName = "Sales",
    Locale = "en-US",
    Currency = "USD"
});

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

ServerSheetControl creates an independent workbook with an initial worksheet. SheetName names that sheet Sales, and the locale and currency options establish the display context. Sheets.AtAsync(0) returns the first worksheet using a zero-based collection index.

The await using statement releases the control and its processing resources when the program finishes. Await each operation before using its result or disposing the control.

2. Write Text and Numeric Values to Cells

Add a report title in A1, a subtitle in A2, and the service data in A4:D8. SetValuesAsync writes a rectangular array, with one inner array per worksheet row. The first array contains the headings, followed by four service records.

await sheet.Cell("A1").SetTextAsync("Monthly Sales Report");
await sheet.Cell("A2").SetTextAsync("Services overview");
await sheet.Range("A4:D8").SetValuesAsync(new object?[][]
{
    ["Service", "Quantity", "Unit price", "Amount"],
    ["Consulting", 3, 120, null],
    ["Training", 2, 90, null],
    ["Support", 5, 45, null],
    ["Hosting", 12, 15, null]
});

Quantities and unit prices are supplied as C# numbers. The empty null entries reserve the Amount cells for the formulas added next. This keeps calculation separate from presentation: a price such as 120 remains numeric even when displayed as $120.00.

SetTextAsync explicitly writes literal text. It is also useful for identifiers that must retain leading zeros or application data that begins with an equals sign.

3. Add Excel Formulas and Calculate the Total

Each Amount cell multiplies its Quantity by its Unit price. The loop writes formulas into D5:D8, and D10 sums those four results.

for (int row = 5; row <= 8; row++)
{
    await sheet.Cell($"D{row}").SetFormulaAsync($"=B{row}*C{row}");
}

await sheet.Cell("A10").SetTextAsync("Grand total");
await sheet.Cell("D10").SetFormulaAsync("=SUM(D5:D8)");
await workbook.RecalculateAsync();

SetFormulaAsync requires a leading equals sign. For example, D5 contains =B5*C5 and calculates to 360. D10 contains =SUM(D5:D8) and calculates to 945. Calling RecalculateAsync explicitly refreshes the workbook calculations before the export.

The XLSX file retains the formulas and requests a full recalculation when opened. Recipients can change quantities or prices in Excel and recalculate the amounts.

4. Format the Worksheet

Apply a consistent font, emphasize the report title, and give the column headings a purple fill with white text. Currency number formats make the prices and amounts readable while preserving their numeric values.

await sheet.Range("A1:D10").FormatAsync(new
{
    fontFamily = "Arial",
    fontSize = 11
});
await sheet.Cell("A1").FormatAsync(new
{
    fontSize = 22,
    bold = true,
    textColor = "#512178"
});
await sheet.Cell("A2").FormatAsync(new { textColor = "#666666" });
await sheet.Range("A4:D4").FormatAsync(new
{
    bold = true,
    textColor = "#ffffff",
    fillColor = "#512178"
});
await sheet.Range("B5:B8").FormatAsync(new { numberFormatCode = "0" });
await sheet.Range("C5:D8").FormatAsync(new { numberFormatCode = "$#,##0.00" });
await sheet.Range("A10:D10").FormatAsync(new
{
    bold = true,
    fillColor = "#eee5f5"
});
await sheet.Cell("D10").FormatAsync(new { numberFormatCode = "$#,##0.00" });

await sheet.Columns.Get("A").SetWidthAsync(new { pixels = 260 });
await sheet.Columns.Get("B").SetWidthAsync(new { pixels = 100 });
await sheet.Columns.Get("C").SetWidthAsync(new { pixels = 140 });
await sheet.Columns.Get("D").SetWidthAsync(new { pixels = 140 });
await sheet.Rows.Get(1).SetHeightAsync(new { pixels = 40 });
await sheet.Rows.Get(4).SetHeightAsync(new { pixels = 28 });

FormatAsync accepts a style object with properties such as fontSize, bold, textColor, fillColor, and numberFormatCode. The $#,##0.00 format displays USD amounts with two decimal places. Column widths and row heights use explicit pixel values in this example; set each column width through its own column handle.

5. Save the Workbook as an Excel XLSX File

Resolve the output path and save the workbook with StreamType.SpreadsheetML. This stream type selects the Excel XLSX format; the filename extension alone does not choose the exporter.

string outputPath = Path.GetFullPath(args.Length > 0 ? args[0] : "sales-report.xlsx");
Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!);
await control.SaveAsync(outputPath, StreamType.SpreadsheetML);

var total = await sheet.Cell("D10").GetValueAsync();
Console.WriteLine($"Created: {outputPath}");
Console.WriteLine($"Grand total: {total.GetDecimal():0.00}");

GetValueAsync reads the calculated value as a JsonElement. Because D10 is numeric in this report, GetDecimal() returns the total for the console output. For cells containing other value types or formula errors, inspect the returned value kind before choosing an accessor.

For an HTTP response or another in-memory workflow, the overload await control.SaveAsync(StreamType.SpreadsheetML) returns a byte[]. An XLSX download uses the content type application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.

Run the Complete Example

The following Program.cs combines all five steps. Replace the generated console program with this code, provide your license file, and run it from the project directory.

using TXTextControl.TXSheetControl.Server;

// 1. Create a workbook.
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,
    SheetName = "Sales",
    Locale = "en-US",
    Currency = "USD"
});

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

// 2. Add text and numeric values.
await sheet.Cell("A1").SetTextAsync("Monthly Sales Report");
await sheet.Cell("A2").SetTextAsync("Services overview");
await sheet.Range("A4:D8").SetValuesAsync(new object?[][]
{
    ["Service", "Quantity", "Unit price", "Amount"],
    ["Consulting", 3, 120, null],
    ["Training", 2, 90, null],
    ["Support", 5, 45, null],
    ["Hosting", 12, 15, null]
});

// 3. Calculate line amounts and the grand total.
for (int row = 5; row <= 8; row++)
{
    await sheet.Cell($"D{row}").SetFormulaAsync($"=B{row}*C{row}");
}

await sheet.Cell("A10").SetTextAsync("Grand total");
await sheet.Cell("D10").SetFormulaAsync("=SUM(D5:D8)");
await workbook.RecalculateAsync();

// 4. Format the report.
await sheet.Range("A1:D10").FormatAsync(new
{
    fontFamily = "Arial",
    fontSize = 11
});
await sheet.Cell("A1").FormatAsync(new
{
    fontSize = 22,
    bold = true,
    textColor = "#512178"
});
await sheet.Cell("A2").FormatAsync(new { textColor = "#666666" });
await sheet.Range("A4:D4").FormatAsync(new
{
    bold = true,
    textColor = "#ffffff",
    fillColor = "#512178"
});
await sheet.Range("B5:B8").FormatAsync(new { numberFormatCode = "0" });
await sheet.Range("C5:D8").FormatAsync(new { numberFormatCode = "$#,##0.00" });
await sheet.Range("A10:D10").FormatAsync(new
{
    bold = true,
    fillColor = "#eee5f5"
});
await sheet.Cell("D10").FormatAsync(new { numberFormatCode = "$#,##0.00" });

await sheet.Columns.Get("A").SetWidthAsync(new { pixels = 260 });
await sheet.Columns.Get("B").SetWidthAsync(new { pixels = 100 });
await sheet.Columns.Get("C").SetWidthAsync(new { pixels = 140 });
await sheet.Columns.Get("D").SetWidthAsync(new { pixels = 140 });
await sheet.Rows.Get(1).SetHeightAsync(new { pixels = 40 });
await sheet.Rows.Get(4).SetHeightAsync(new { pixels = 28 });

// 5. Save an Excel XLSX file.
string outputPath = Path.GetFullPath(args.Length > 0 ? args[0] : "sales-report.xlsx");
Directory.CreateDirectory(Path.GetDirectoryName(outputPath)!);
await control.SaveAsync(outputPath, StreamType.SpreadsheetML);

var total = await sheet.Cell("D10").GetValueAsync();
Console.WriteLine($"Created: {outputPath}");
Console.WriteLine($"Grand total: {total.GetDecimal():0.00}");
dotnet run -- sales-report.xlsx

The application prints the full output path and a grand total of 945.00. Open the generated workbook in Microsoft Excel or the TX Sheet Control editor. The following screenshot shows the actual XLSX produced by this sample, opened in the editor with D10 selected so that its formula is visible.

Generated sales-report.xlsx with four service lines, currency formatting, and the selected SUM formula totaling $945.00
The generated XLSX retains its values, formulas, column widths, and formatting. D10 calculates the grand total of $945.00.

Use the Same Workflow in Your Application

Replace the sample rows with data from your application, retaining numeric values for quantities and prices. Calculate the last data row when constructing formula ranges for a variable number of records. For unrelated export jobs, use separate controls or explicitly managed document sessions.

When deploying, include the complete build or publish output so the processing engine and packaged assets remain available. Supply the license through your deployment configuration or an accessible license file.

Continue with the .NET spreadsheet processing tutorial, the ServerSheetControl API reference, and the loading and saving guide. To add interactive editing to a web application, see Getting Started with TX Sheet Control in ASP.NET Core.

Download trial

Frequently Asked Questions

No. TX Sheet Control processes the workbook with its server engine. This console example does not automate Microsoft Excel or require a browser.

The example uses TXTextControl.TXSheetControl.Server 2.0.0 and .NET 10. Configure the Text Control NuGet feed or use the NuGet folder from the product download.

The sample reads the signed license from tx-sheet-control.license in the working directory. Set TX_SHEET_LICENSE_PATH to use a different file location. Pass the file contents to ServerSheetControlOptions.License.

Yes. The sample exports the formulas in D5:D8 and D10, and the XLSX requests recalculation when opened. Recipients can edit the quantities or prices in Excel and recalculate the report.

Write a numeric value and apply a numberFormatCode such as $#,##0.00 with FormatAsync. The number remains available for calculations.

Yes. SaveAsync(StreamType.SpreadsheetML) returns a byte array. A web application can return those bytes with the XLSX MIME type and a download filename.

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

AngularExcelGetting Started

How to Add a Spreadsheet Editor to an Angular Application

Add a complete spreadsheet editor to an Angular application using TX Sheet Control. This tutorial configures the standalone component and its assets, loads Excel workbooks, changes cells and…


BlazorBlazor WebAssemblyC#

Getting Started with TX Sheet Control in Blazor WebAssembly

Build your first Blazor WebAssembly spreadsheet application with TX Sheet Control. Configure the license, editor areas, and ribbon, load workbooks and CSV data, and edit cell text, values, and…


BlazorBlazor ServerC#

Getting Started with TX Sheet Control in Blazor Server

Build your first Blazor Server spreadsheet application with TX Sheet Control. Configure the license, editor areas, and ribbon, load workbooks and CSV data, and edit cell text, values, and formulas…


ExcelSpreadsheetXLSX

Excel Compatibility in TX Sheet Control: Working with the Workbooks Your…

Learn how TX Sheet Control loads, edits, and saves Excel XLSX workbooks with their formulas, formatting, tables, charts, and native pivot tables. This article covers conversion diagnostics,…


AngularBlazorJavaScript

TX Sheet Control 2.0 Is Now Available: Spreadsheets and Dashboards for Your…

Today, we are proud to officially release TX Sheet Control 2.0. The newest member of the Text Control product family brings Excel-compatible spreadsheet editing, a powerful calculation engine,…

Share this blog post on:

​​​