Skip to footer content
USING IRONXL

Build an Excel API for .NET Core: Create, Read, and Export XLSX Files

Working with Excel files programmatically opens up powerful possibilities for server side web applications—from generating data-driven Excel reports to importing data from user-uploaded spreadsheets. IronXL stands out among .NET Excel API libraries, providing a complete .NET Excel API that handles Microsoft Excel document formats without requiring Microsoft Office installation, making it ideal for building robust Excel functionality into your cross platform .NET Core applications.

This tutorial demonstrates how to build an Excel API for .NET Core using IronXL, covering everything from creating new Excel workbooks to reading existing XLSX files and exporting data to different formats. Get started with a free trial to follow along.

How Do You Create Excel Files Programmatically in .NET Core?

Creating Excel documents from scratch requires just a few lines of code with IronXL's intuitive .NET Excel library. The API provides complete control over Excel workbooks, worksheets, cell styles, and formulas through a clean object model.

First, install the IronXL NuGet package in your ASP.NET Core project:

Install-Package IronXL.Excel

Here's a controller action that creates a new Excel workbook with formatted data, demonstrates worksheet management, and applies cell styles to format cells:

using IronXL;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ExcelController : ControllerBase
{
    [HttpGet("create-report")]
    public IActionResult CreateSalesReport()
    {
        // Create a new Excel workbook
        WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
        WorkSheet worksheet = workbook.CreateWorkSheet("Sales Data");
        // Set headers with cell styles
        worksheet["A1"].Value = "Product";
        worksheet["B1"].Value = "Q1 Sales";
        worksheet["C1"].Value = "Q2 Sales";
        worksheet["D1"].Value = "Total";
        // Apply bold formatting to header row
        worksheet["A1:D1"].Style.Font.Bold = true;
        worksheet["A1:D1"].Style.SetBackgroundColor("#4472C4");
        worksheet["A1:D1"].Style.Font.SetColor("#FFFFFF");
        // Add Excel data with number formats
        worksheet["A2"].Value = "Widget Pro";
        worksheet["B2"].Value = 15000;
        worksheet["C2"].Value = 18500;
        worksheet["D2"].Formula = "=B2+C2";
        worksheet["A3"].Value = "Gadget Plus";
        worksheet["B3"].Value = 22000;
        worksheet["C3"].Value = 24000;
        worksheet["D3"].Formula = "=B3+C3";
        // Apply currency number formats to sales columns
        worksheet["B2:D3"].Style.Format = "$#,##0";
        // Save and return the XLSX file
        var stream = workbook.ToStream();
        return File(stream,
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "SalesReport.xlsx");
    }
}
using IronXL;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ExcelController : ControllerBase
{
    [HttpGet("create-report")]
    public IActionResult CreateSalesReport()
    {
        // Create a new Excel workbook
        WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
        WorkSheet worksheet = workbook.CreateWorkSheet("Sales Data");
        // Set headers with cell styles
        worksheet["A1"].Value = "Product";
        worksheet["B1"].Value = "Q1 Sales";
        worksheet["C1"].Value = "Q2 Sales";
        worksheet["D1"].Value = "Total";
        // Apply bold formatting to header row
        worksheet["A1:D1"].Style.Font.Bold = true;
        worksheet["A1:D1"].Style.SetBackgroundColor("#4472C4");
        worksheet["A1:D1"].Style.Font.SetColor("#FFFFFF");
        // Add Excel data with number formats
        worksheet["A2"].Value = "Widget Pro";
        worksheet["B2"].Value = 15000;
        worksheet["C2"].Value = 18500;
        worksheet["D2"].Formula = "=B2+C2";
        worksheet["A3"].Value = "Gadget Plus";
        worksheet["B3"].Value = 22000;
        worksheet["C3"].Value = 24000;
        worksheet["D3"].Formula = "=B3+C3";
        // Apply currency number formats to sales columns
        worksheet["B2:D3"].Style.Format = "$#,##0";
        // Save and return the XLSX file
        var stream = workbook.ToStream();
        return File(stream,
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "SalesReport.xlsx");
    }
}
$vbLabelText   $csharpLabel

Output Excel File

Build an Excel API for .NET Core: Create, Read, and Export XLSX Files: Image 1 - Excel file generated by our .NET Core API

This code creates a new Excel workbook using WorkBook.Create(), which supports both XLSX and XLS formats. The CreateWorkSheet() method adds Excel worksheets where you can populate spreadsheet cells with values, create formulas for complex calculations, and organize data into Excel tables and data tables. You can easily manage table columns, create formulas, and apply cell styles including fonts, colors, and number formats. IronXL's calculation engine automatically evaluates formulas when the workbook data changes, supporting advanced Microsoft Excel formulas including array formula support for complex data analysis.

What Is the Best Way to Read Excel Data in Web APIs?

Importing data from user-uploaded Excel files is essential for web applications that process spreadsheet content. IronXL makes reading Excel spreadsheets straightforward, allowing you to sort data or filter data based on custom criteria, whether working with XLSX files, XLS, or CSV formats.

[HttpPost("import")]
public IActionResult ImportExcelData(IFormFile file)
{
    if (file == null || file.Length == 0)
        return BadRequest("No file uploaded");
    using var stream = file.OpenReadStream();
    WorkBook workbook = WorkBook.Load(stream);
    WorkSheet worksheet = workbook.DefaultWorkSheet;
    var records = new List<Dictionary<string, object>>();
    // Read cell range starting from row 2 (skip headers)
    for (int row = 2; row <= worksheet.RowCount; row++)
    {
        var record = new Dictionary<string, object>
        {
            ["Product"] = worksheet[$"A{row}"].StringValue,
            ["Sales"] = worksheet[$"B{row}"].DecimalValue,
            ["Date"] = worksheet[$"C{row}"].DateTimeValue
        };
        records.Add(record);
    }
    return Ok(new {
        message = "Import successful",
        recordCount = records.Count,
        data = records
    });
}
[HttpPost("import")]
public IActionResult ImportExcelData(IFormFile file)
{
    if (file == null || file.Length == 0)
        return BadRequest("No file uploaded");
    using var stream = file.OpenReadStream();
    WorkBook workbook = WorkBook.Load(stream);
    WorkSheet worksheet = workbook.DefaultWorkSheet;
    var records = new List<Dictionary<string, object>>();
    // Read cell range starting from row 2 (skip headers)
    for (int row = 2; row <= worksheet.RowCount; row++)
    {
        var record = new Dictionary<string, object>
        {
            ["Product"] = worksheet[$"A{row}"].StringValue,
            ["Sales"] = worksheet[$"B{row}"].DecimalValue,
            ["Date"] = worksheet[$"C{row}"].DateTimeValue
        };
        records.Add(record);
    }
    return Ok(new {
        message = "Import successful",
        recordCount = records.Count,
        data = records
    });
}
$vbLabelText   $csharpLabel

Output

Build an Excel API for .NET Core: Create, Read, and Export XLSX Files: Image 2 - Output showing our successfully imported Excel data

The WorkBook.Load() method opens Excel files from streams, file paths, or byte arrays, enabling users to import data from external files uploaded through your API. You can access individual cell values using the intuitive worksheet["A1"] syntax or iterate through a cell range. IronXL handles data validation automatically and provides type-safe accessors like IntValue, DecimalValue, and DateTimeValue for reliable data extraction from worksheet cells.

How Can You Export Excel Data to Different Formats?

Modern applications often need to export spreadsheets to multiple formats for interactive reporting and tracking performance. IronXL supports exporting data to XLSX, XLS, CSV, JSON, and HTML, making it easy to present data across different web pages and various image formats.

[HttpGet("export/{format}")]
public IActionResult ExportData(string format)
{
    WorkBook workbook = WorkBook.Load("template.xlsx");
    return format.ToLower() switch
    {
        "xlsx" => File(workbook.ToStream(),
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "export.xlsx"),
        "csv" => File(workbook.ToStream(FileFormat.CSV),
            "text/csv",
            "export.csv"),
        "json" => Ok(workbook.ToJson()),
        _ => BadRequest("Unsupported format")
    };
}
[HttpGet("export/{format}")]
public IActionResult ExportData(string format)
{
    WorkBook workbook = WorkBook.Load("template.xlsx");
    return format.ToLower() switch
    {
        "xlsx" => File(workbook.ToStream(),
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "export.xlsx"),
        "csv" => File(workbook.ToStream(FileFormat.CSV),
            "text/csv",
            "export.csv"),
        "json" => Ok(workbook.ToJson()),
        _ => BadRequest("Unsupported format")
    };
}
$vbLabelText   $csharpLabel

Using Excel templates with predefined layouts accelerates report generation by letting you load pre-designed spreadsheets and populate them with dynamic workbook data. This approach works especially well for sales reports, invoices, and data-driven Excel reports where consistent formatting matters. IronXL's cross-platform support means these file operations work identically on Windows, Linux, and macOS, perfect for .NET Core and .NET Framework deployments.

Conclusion

Building an Excel API with IronXL gives your .NET Core applications powerful capabilities for working with Excel documents. From creating XLSX files with formatted data and complex formulas to importing user uploads and exporting data to multiple formats, IronXL's .NET Excel API simplifies every aspect of spreadsheet manipulation.

The library handles advanced features like data bars, conditional formatting rules, line charts, and pivot charts efficiently. For professional applications, it also provides password protection, digital signatures, and form controls to ensure your XLSX reports and .NET Excel reports are secure and functional. Even when handling large spreadsheets, IronXL maintains high performance without Microsoft Office dependencies.

Ready to add Excel functionality to your .NET applications? Explore licensing options or start your free trial to experience the full capabilities of this powerful .NET Excel library.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he ...
Read More