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

- **Author:** Bjoern Meyer
- **Published:** 2026-12-03
- **Modified:** 2026-12-03
- **Description:** 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.
- **7 min read** (1287 words)
- **Tags:**
  - Spreadsheet
  - XLSX
  - Excel
  - C#
  - .NET
  - Document Generation
- **Web URL:** https://www.textcontrol.com/blog/2026/12/03/how-to-create-an-excel-xlsx-file-in-csharp-dotnet/
- **LLMs URL:** https://www.textcontrol.com/blog/2026/12/03/how-to-create-an-excel-xlsx-file-in-csharp-dotnet/llms.txt
- **LLMs-Full URL:** https://www.textcontrol.com/blog/2026/12/03/how-to-create-an-excel-xlsx-file-in-csharp-dotnet/llms-full.txt

---

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](https://docs.textcontrol.com/tx-sheet-control/installation/nuget/) 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](https://s1-www.textcontrol.com/assets/dist/blog/2026/12/03/a/assets/generated-sales-workbook.webp "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](https://docs.textcontrol.com/tx-sheet-control/getting-started/document-processing/dotnet/), the [ServerSheetControl API reference](https://docs.textcontrol.com/tx-sheet-control/reference/dotnet-api/txtextcontrol-txsheetcontrol-server/serversheetcontrol/), and the [loading and saving guide](https://docs.textcontrol.com/tx-sheet-control/document-processing/load-save/). To add interactive editing to a web application, see [Getting Started with TX Sheet Control in ASP.NET Core](https://www.textcontrol.com/blog/2026/12/02/getting-started-with-tx-sheet-control-in-aspnet-core/llms-full.txt).

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

### Frequently Asked Questions

Do I need Microsoft Excel installed to generate an XLSX file? 
--------------------------------------------------------------

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

Which NuGet package and .NET version does the sample use? 
----------------------------------------------------------

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.

How is the TX Sheet Control license configured? 
------------------------------------------------

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.

Are formulas preserved in the exported Excel file? 
---------------------------------------------------

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.

How do I format a number as currency without converting it to text? 
--------------------------------------------------------------------

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

Can I create the XLSX in memory instead of writing it to disk? 
---------------------------------------------------------------

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

---

## 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 Add a Spreadsheet Editor to an Angular Application](https://www.textcontrol.com/blog/2026/12/03/how-to-add-a-spreadsheet-editor-to-an-angular-application/llms.txt)
- [Getting Started with TX Sheet Control in Blazor WebAssembly](https://www.textcontrol.com/blog/2026/12/02/getting-started-with-tx-sheet-control-in-blazor-webassembly/llms.txt)
- [Getting Started with TX Sheet Control in Blazor Server](https://www.textcontrol.com/blog/2026/12/02/getting-started-with-tx-sheet-control-in-blazor-server/llms.txt)
- [Excel Compatibility in TX Sheet Control: Working with the Workbooks Your Users Already Have](https://www.textcontrol.com/blog/2026/12/01/excel-compatibility-in-tx-sheet-control/llms.txt)
- [TX Sheet Control 2.0 Is Now Available: Spreadsheets and Dashboards for Your Applications](https://www.textcontrol.com/blog/2026/12/01/tx-sheet-control-2-0-is-now-available/llms.txt)
- [Importing Excel XLSX Spreadsheets into TX Text Control in ASP.NET Core and Windows Forms in C#](https://www.textcontrol.com/blog/2023/02/07/importing-excel-xlsx-spreadsheets-into-tx-text-control/llms.txt)
