Generate Excel File in C# – Create and Export in .NET & ASP.NET

Generate Excel file using C# and Spire.XLS in .NET and ASP.NET applications

Generating Excel files in C# is a common task for developers building reporting systems, exporting structured data, or automating Excel-based workflows. Whether you're building desktop tools, web APIs with ASP.NET Core, or cross-platform apps using .NET, the ability to generate .xlsx files programmatically can simplify many data exchange scenarios.

In this guide, you'll learn how to generate Excel files in C# using Spire.XLS for .NET — a standalone Excel library that works seamlessly across different types of .NET applications — from desktop tools to web services and background jobs. We’ll cover use cases such as creating spreadsheets from scratch, exporting data from a DataTable, generating files on the server side, and applying formatting or formulas, all with practical code examples.

Table of Contents


Set Up the Environment

Spire.XLS for .NET is a lightweight Excel library that allows you to create .xlsx/.xls files entirely through code — without installing Microsoft Office or using COM Interop. This makes it an ideal solution for web servers, microservices, and cloud-hosted applications.

You can install the library via NuGet:

Install-Package Spire.XLS

For smaller tasks, Free Spire.XLS for .NET is also a good choice:

Install-Package FreeSpire.XLS

Create Excel Files from Scratch in C#

For simple tasks like configuration files, small datasets, or template generation, creating an Excel file from scratch in C# provides full control over content and layout.

The example below shows how to generate a basic worksheet with text and numeric data:

using Spire.Xls;

// Create a new workbook and worksheet
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "Summary";

// Fill in headers and data
// Access cells by name
sheet.Range["A1"].Text = "Employee";
sheet.Range["B1"].Text = "Department";
sheet.Range["C1"].Text = "Salary";

// Access cells by row and column
sheet.Range[2, 1].Text = "Alice";
sheet.Range[2, 2].Text = "HR";
sheet.Range[2, 3].NumberValue = 6500;

sheet.Range[3, 1].Text = "Bob";
sheet.Range[3, 2].Text = "IT";
sheet.Range[3, 3].NumberValue = 7200;

// Apply styles
CellStyle headerStyle = workbook.Styles.Add("Header");
headerStyle.Font.IsBold = true;
sheet.Range["A1:C1"].Style = headerStyle;
// sheet.Range[1, 1, 1, 3].Style = headerStyle;

// Auto-fit columns
sheet.AllocatedRange.AutoFitColumns();

// Save the file
workbook.SaveToFile("BasicExcel.xlsx", ExcelVersion.Version2016);
workbook.Dispose();

Example output: A basic Excel file with employee names, departments, and salaries created in C#.

Basic Excel file generated in C# showing employee, department, and salary data

This approach works entirely without Excel installed, and is ideal for lightweight, structured exports.


Export DataTable to Excel in C#

When working with databases or APIs, exporting a DataTable directly to Excel in C# is often necessary. Instead of looping through rows manually, Spire.XLS provides an efficient way to load structured data in one line.

Here’s how you can convert a DataTable into a worksheet, including headers:

using System.Data;
using Spire.Xls;

// Create a simulated data table
DataTable dt = new DataTable("Products");
dt.Columns.Add("Product Name", typeof(string));
dt.Columns.Add("Price", typeof(double));
dt.Columns.Add("Stock", typeof(int));

dt.Rows.Add("Laptop", 1299.99, 20);
dt.Rows.Add("Monitor", 199.5, 50);
dt.Rows.Add("Mouse", 25.75, 150);

// Import into Excel
Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "Inventory";
sheet.InsertDataTable(dt, true, 1, 1);

// Auto-fit column widths
sheet.AllocatedRange.AutoFitColumns();

// Save the file
workbook.SaveToFile("InventoryReport.xlsx", ExcelVersion.Version2016);
workbook.Dispose();

Example output: Excel spreadsheet generated from a DataTable containing product details, prices, and stock levels.

Excel file exported from C# DataTable with product name, price, and stock columns

This is a common approach for exporting reports, inventory lists, and analytics — with no Excel or Interop automation required.

Related article: Convert Data Between Excel Files and DataTable in C#


Apply Formatting and Formulas in Excel Using C#

In addition to exporting raw data, you can generate professional Excel files in C# by applying formatting, styling, and formulas — improving readability and enabling automatic calculations.

Below is an example that demonstrates basic styling and formula use:

using Spire.Xls;
using System.Drawing;

Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "Sales Report";

// Set header labels
sheet.Range["A1"].Text = "Item";
sheet.Range["B1"].Text = "Price";
sheet.Range["C1"].Text = "Quantity";
sheet.Range["D1"].Text = "Total";

// Add sample data
string[,] items = {
    { "Pen", "1.5", "10" },
    { "Notebook", "3.75", "5" },
    { "Eraser", "0.99", "20" }
};

for (int i = 0; i < items.GetLength(0); i++)
{
    int row = i + 2;
    sheet.Range[$"A{row}"].Text = items[i, 0];
    sheet.Range[$"B{row}"].NumberValue = double.Parse(items[i, 1]);
    sheet.Range[$"C{row}"].NumberValue = double.Parse(items[i, 2]);
    sheet.Range[$"D{row}"].Formula = $"=B{row}*C{row}";
}

// Style: Header row
CellStyle headerStyle = workbook.Styles.Add("HeaderStyle");
headerStyle.Font.IsBold = true;
headerStyle.Font.Color = Color.White;
headerStyle.Font.Size = 12;
headerStyle.KnownColor = ExcelColors.DarkBlue;
headerStyle.HorizontalAlignment = HorizontalAlignType.Center;
headerStyle.VerticalAlignment = VerticalAlignType.Center;
headerStyle.Borders[BordersLineType.EdgeTop].LineStyle = LineStyleType.Thick;
headerStyle.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thick;
sheet.Range["A1:D1"].Style = headerStyle;
sheet.Range["A1:D1"].RowHeight = 22;

// Style: Data cells
CellStyle dataStyle = workbook.Styles.Add("DataStyle");
dataStyle.NumberFormat = "\"$\"#,##0.00";
dataStyle.HorizontalAlignment = HorizontalAlignType.Right;
dataStyle.VerticalAlignment = VerticalAlignType.Center;
dataStyle.Borders[BordersLineType.EdgeLeft].LineStyle = LineStyleType.Thin;
dataStyle.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Thin;

// Apply data style to Price, Quantity, Total
sheet.Range["B2:D4"].Style = dataStyle;

// Optional: Alternating row colors for readability
for (int r = 2; r <= 4; r++)
{
    if (r % 2 == 0)
        sheet.Range[$"A{r}:D{r}"].Style.KnownColor = ExcelColors.LightYellow;
}

// Adjust widths and heights
sheet.AllocatedRange.AutoFitColumns();
sheet.AllocatedRange.RowHeight = 20;

// Save file
workbook.SaveToFile("styled.xlsx", FileFormat.Version2016);
workbook.Dispose();

Example output: A styled Excel sheet with headers, formulas, alternating row colors, and formatted currency values.

C# generated Excel file with styled headers, currency formatting, formulas, and alternating row colors

By using C# and Spire.XLS, you can apply styles, borders, colors, alignments, and Excel-compatible formulas to generate clean, automated, and user-friendly Excel reports.

To further enhance your Excel reports, you can also apply number formats such as currency, percentage, or custom formats. Learn more about setting number formats in C#


Generate Excel Files in ASP.NET Core

In modern ASP.NET Core applications (e.g., .NET 6/7/8), generating Excel files is a common requirement for admin dashboards, data exports, and reporting features. The example below shows how to generate an Excel file on the server and return it as a downloadable file from a Razor Page handler.

Here’s how you can implement it in a Razor Pages project:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Spire.Xls;
using System.Data;

public class ExportModel : PageModel
{
    public IActionResult OnGet()
    {
        // Simulated data
        DataTable dt = new DataTable("Sales");
        dt.Columns.Add("Date", typeof(DateTime));
        dt.Columns.Add("Product", typeof(string));
        dt.Columns.Add("Revenue", typeof(double));

        dt.Rows.Add(DateTime.Today.AddDays(-2), "Laptop", 1250.00);
        dt.Rows.Add(DateTime.Today.AddDays(-1), "Monitor", 320.50);
        dt.Rows.Add(DateTime.Today, "Mouse", 25.99);

        // Create Excel workbook and sheet
        Workbook workbook = new Workbook();
        Worksheet sheet = workbook.Worksheets[0];
        sheet.Name = "DailySales";

        // Insert data
        sheet.InsertDataTable(dt, true, 1, 1);

        // Apply simple header style
        CellStyle headerStyle = workbook.Styles.Add("HeaderStyle");
        headerStyle.Font.IsBold = true;
        sheet.Rows[0].Style = headerStyle;
        sheet.AllocatedRange.AutoFitColumns();

        // Save to memory stream
        using var stream = new MemoryStream();
        workbook.SaveToStream(stream, FileFormat.Version2016);
        stream.Position = 0;

        // Return file to browser
        return File(stream.ToArray(),
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "SalesReport.xlsx");
    }
}

Example output: Daily sales report generated in a .NET 8 console app with date, product, and revenue columns.

.NET Core Excel export showing daily sales with date, product, and revenue

This method is ideal for web-based reporting tools, internal portals, and admin dashboards that require dynamic Excel downloads.

  • ✅ Works in ASP.NET Core 3.1, .NET 5, .NET 6, .NET 7, .NET 8
  • ✅ Suitable for: Razor Pages, MVC, and API endpoints with file download support

Generate Excel Files in ASP.NET Web Forms

If you're building an internal admin panel or classic ASP.NET Web Forms application, you may want to allow users to download Excel files directly from the browser. The example below demonstrates how to create an Excel file entirely in memory and return it in the HTTP response for immediate download — without saving it to disk.

using Spire.Xls;
using System;
using System.IO;

namespace YourNamespace
{
    public partial class Default : System.Web.UI.Page
    {
        protected void btnExport_Click(object sender, EventArgs e)
        {
            // Create Excel file and output for download
            Workbook workbook = new Workbook();
            Worksheet sheet = workbook.Worksheets[0];
            sheet.Name = "Users";

            // Headers
            string[] headers = { "ID", "Name", "Department", "Join Date" };
            for (int i = 0; i < headers.Length; i++)
            {
                sheet.Range[1, i + 1].Text = headers[i];
                sheet.Range[1, i + 1].Style.Font.IsBold = true;
            }

            // Sample data
            string[,] data = {
                { "U001", "Gemma", "HR", "2023-01-15" },
                { "U002", "Bill", "IT", "2022-11-03" }
            };

            // Fill data
            for (int r = 0; r < data.GetLength(0); r++)
                for (int c = 0; c < data.GetLength(1); c++)
                    sheet.Range[r + 2, c + 1].Text = data[r, c];

            // Auto-fit column widths
            sheet.AllocatedRange.AutoFitColumns();

            // Export for browser download
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.SaveToStream(ms, FileFormat.Version2016);
                byte[] bytes = ms.ToArray();
                Response.Clear();
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("Content-Disposition", "attachment; filename=Users.xlsx");
                Response.BinaryWrite(bytes);
                Response.End();
            }
        }
    }
}

Example output: Excel file created and streamed to browser in ASP.NET containing employee records.

ASP.NET-generated Excel file with employee ID, name, and department

This pattern allows Excel files to be generated and downloaded dynamically, without writing to disk or requiring Office installed on the server.


FAQ

How to create an Excel file from C#?

You can use a library like Spire.XLS to create a new workbook, write data to worksheets, and save it as an Excel file — all without Office installed.

How to export an Excel file in C#?

If you want to export data (e.g. from a DataTable), you can load it into a worksheet and save the file using Spire.XLS. It supports automatic column headers and formatting.

How to generate Excel files in ASP.NET using C#?

You can generate Excel files in both ASP.NET Web Forms and ASP.NET Core using Spire.XLS. In ASP.NET Core, create the file in memory and return it in the HTTP response. In Web Forms, use a similar approach with Response.BinaryWrite() to stream the file to the browser.

Is Spire.XLS compatible with .NET Core?

Yes. It supports .NET Core 3.1+, .NET 5, .NET 6, .NET 7, and .NET 8, making it suitable for cross-platform Excel generation.


Conclusion

With Spire.XLS for .NET, you can easily generate Excel files in C# for any scenario — including desktop, ASP.NET Core, and classic Web Forms applications. Whether you need to export a DataTable, generate formatted reports, or automate Excel output, this guide helps you build Excel files in C# with zero dependencies.

Apply for a Free Temporary License to unlock all features and remove evaluation warnings.