Skip to footer content
USING IRONXL

Blazor Export to Excel: Complete Guide Using IronXL in C#

Exporting data to Excel is something almost every web app needs, whether it’s for generating reports, inventory lists, or customer invoices. In a Blazor Server application, reliably accomplishing this without requiring Microsoft Office can be challenging. That’s where IronXL comes in. It allows you to create, format, and download Excel files directly from your server, with no Office installation required, and integrates seamlessly with Blazor. In this guide, you’ll see just how simple it is to add professional Excel export features to your app. Let's get started.

Getting Started with IronXL to Export Data to Excel

Setting up IronXL in a Blazor Server application requires minimal configuration. Start by creating a new Blazor Server project in Visual Studio 2022 or later, targeting .NET 6 or above.

Install IronXL through the NuGet Package Manager Console (see our complete installation guide for alternative methods):

Install-Package IronXL
Install-Package IronXL
SHELL

Next, create a JavaScript helper function for file downloads. In your wwwroot folder, add a new JavaScript file called excelExport.js:

window.downloadFileFromStream = async (fileName, contentStreamReference) => {
    const arrayBuffer = await contentStreamReference.arrayBuffer();
    const blob = new Blob([arrayBuffer]);
    const url = URL.createObjectURL(blob);
    const anchorElement = document.createElement('a');
    anchorElement.href = url;
    anchorElement.download = fileName ?? 'export.xlsx';
    anchorElement.click();
    anchorElement.remove();
    URL.revokeObjectURL(url);
}
window.downloadFileFromStream = async (fileName, contentStreamReference) => {
    const arrayBuffer = await contentStreamReference.arrayBuffer();
    const blob = new Blob([arrayBuffer]);
    const url = URL.createObjectURL(blob);
    const anchorElement = document.createElement('a');
    anchorElement.href = url;
    anchorElement.download = fileName ?? 'export.xlsx';
    anchorElement.click();
    anchorElement.remove();
    URL.revokeObjectURL(url);
}
JAVASCRIPT

Include this script in your _Host.cshtml file:

<script src="~/excelExport.js"></script>
<script src="~/excelExport.js"></script>
HTML

This JavaScript function handles the browser-side download mechanism, converting the byte stream from your Blazor Server application into a downloadable file. The function creates a temporary blob URL, triggers the download, and cleans up resources to prevent memory leaks.

How to Export a Data Source to Excel Files with IronXL?

Create an Excel export service to handle your business logic. This service encapsulates IronXL functionality and provides reusable methods for different export scenarios in your Blazor Excel export implementation:

using IronXL;
using System.IO;
using ExportExcel.Models;
public class ExcelExportService
{
    public byte[] GenerateSalesReport(List<SalesData> salesData)
    {
        try
        {
            var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
            workbook.Metadata.Author = "Sales Department";
            var worksheet = workbook.CreateWorkSheet("Monthly Sales");
            worksheet["A1"].Value = "Date";
            worksheet["B1"].Value = "Product";
            worksheet["C1"].Value = "Quantity";
            worksheet["D1"].Value = "Revenue";
            worksheet["E1"].Value = "Profit Margin";
            var headerRange = worksheet["A1:E1"];
            headerRange.Style.Font.Bold = true;
            headerRange.Style.BackgroundColor = "#4472C4";
            headerRange.Style.Font.Color = "#FFFFFF";
            int row = 2;
            foreach (var sale in salesData)
            {
                worksheet[$"A{row}"].Value = sale.Date.ToString("yyyy-MM-dd");
                worksheet[$"B{row}"].Value = sale.Product ?? "Unknown";
                worksheet[$"C{row}"].Value = sale.Quantity;
                worksheet[$"D{row}"].Value = sale.Revenue;
                worksheet[$"E{row}"].Value = $"=D{row}*0.15";
                row++;
            }
            worksheet.AutoSizeColumn(0, true);
            using var ms = workbook.ToStream();
            return ms.ToArray();
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("Failed to generate sales report", ex);
        }
    }
}
using IronXL;
using System.IO;
using ExportExcel.Models;
public class ExcelExportService
{
    public byte[] GenerateSalesReport(List<SalesData> salesData)
    {
        try
        {
            var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
            workbook.Metadata.Author = "Sales Department";
            var worksheet = workbook.CreateWorkSheet("Monthly Sales");
            worksheet["A1"].Value = "Date";
            worksheet["B1"].Value = "Product";
            worksheet["C1"].Value = "Quantity";
            worksheet["D1"].Value = "Revenue";
            worksheet["E1"].Value = "Profit Margin";
            var headerRange = worksheet["A1:E1"];
            headerRange.Style.Font.Bold = true;
            headerRange.Style.BackgroundColor = "#4472C4";
            headerRange.Style.Font.Color = "#FFFFFF";
            int row = 2;
            foreach (var sale in salesData)
            {
                worksheet[$"A{row}"].Value = sale.Date.ToString("yyyy-MM-dd");
                worksheet[$"B{row}"].Value = sale.Product ?? "Unknown";
                worksheet[$"C{row}"].Value = sale.Quantity;
                worksheet[$"D{row}"].Value = sale.Revenue;
                worksheet[$"E{row}"].Value = $"=D{row}*0.15";
                row++;
            }
            worksheet.AutoSizeColumn(0, true);
            using var ms = workbook.ToStream();
            return ms.ToArray();
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("Failed to generate sales report", ex);
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This service demonstrates key IronXL features, including creating new workbooks and worksheets, adding formatted headers, populating data rows with imported data from your data source, applying formulas, and handling potential errors. The AutoSizeColumn method ensures that columns display properly, regardless of the content length. For more advanced formatting options, explore our cell styling guide.

How Do You Implement the File Download in Blazor?

Create a Razor component that uses the export service and handles user interaction:

@page "/excel-export"
@using ExportExcel.Models
@inject ExcelExportService ExcelService
@inject IJSRuntime JS
<h3>Excel Export Dashboard</h3>
<div class="export-section">
    <button class="btn btn-primary" @onclick="ExportSalesReport" disabled="@isExporting">
        @if (isExporting)
        {
            <span>Generating...</span>
        }
        else
        {
            <span>Export Sales Report</span>
        }
    </button>
    @if (!string.IsNullOrEmpty(errorMessage))
    {
        <div class="alert alert-danger mt-2">@errorMessage</div>
    }
</div>
@code {
    private bool isExporting = false;
    private string errorMessage = "";
    private async Task ExportSalesReport()
    {
        try
        {
            isExporting = true;
            errorMessage = "";
            var salesData = GetSalesData();
            var fileBytes = ExcelService.GenerateSalesReport(salesData);
            using var stream = new MemoryStream(fileBytes);
            using var streamRef = new DotNetStreamReference(stream);
            await JS.InvokeVoidAsync("downloadFileFromStream",
                $"SalesReport_{DateTime.Now:yyyyMMdd}.xlsx", streamRef);
        }
        catch (Exception ex)
        {
            errorMessage = "Export failed. Please try again.";
        }
        finally
        {
            isExporting = false;
        }
    }
    private List<SalesData> GetSalesData()
    {
        return new List<SalesData>
        {
            new() { Date = DateTime.Now, Product = "Widget A",
                   Quantity = 100, Revenue = 5000 },
            new() { Date = DateTime.Now.AddDays(-1), Product = "Widget B",
                   Quantity = 75, Revenue = 3750 }
        };
    }
}

This component provides user feedback during export, handles errors gracefully, and generates timestamped filenames. The DotNetStreamReference wrapper enables efficient streaming of binary data to JavaScript.

Output

When we run our code, we will see our page loaded with the button that will be used to handle the exporting process.

Blazor Export to Excel: Complete Guide Using IronXL in C#: Image 1 - Sample Blazor page

When we click the button, the data will be saved in a new Excel document, and the exported file will be downloaded.

Blazor Export to Excel: Complete Guide Using IronXL in C#: Image 2 - Data exported to an Excel file

What Advanced Features Can IronXL Add to Your Excel Export?

IronXL supports sophisticated Excel features for professional-looking exports. For an inventory management scenario, you might add conditional formatting and multiple worksheets:

using IronXL;
using ExportExcel.Models;
using System.IO;
namespace ExportExcel.Services
{
    public class InventoryExportService
    {
        public byte[] GenerateInventoryReport(List<InventoryItem> items)
        {
            var workbook = WorkBook.Create();
            var details = workbook.CreateWorkSheet("Inventory Details");
            details["A1"].Value = "SKU";
            details["B1"].Value = "Name";
            details["C1"].Value = "Quantity";
            var headerRange = details["A1:C1"];
            headerRange.Style.Font.Bold = true;
            for (int i = 0; i < items.Count; i++)
            {
                var row = i + 2;
                var item = items[i];
                details[$"A{row}"].Value = item.SKU;
                details[$"B{row}"].Value = item.Name;
                details[$"C{row}"].Value = item.Quantity;
                if (item.Quantity < item.ReorderLevel)
                {
                    details[$"C{row}"].Style.BackgroundColor = "#FFB6B6";
                }
            }
            using var stream = workbook.ToStream();
            return stream.ToArray();
        }
    }
}
using IronXL;
using ExportExcel.Models;
using System.IO;
namespace ExportExcel.Services
{
    public class InventoryExportService
    {
        public byte[] GenerateInventoryReport(List<InventoryItem> items)
        {
            var workbook = WorkBook.Create();
            var details = workbook.CreateWorkSheet("Inventory Details");
            details["A1"].Value = "SKU";
            details["B1"].Value = "Name";
            details["C1"].Value = "Quantity";
            var headerRange = details["A1:C1"];
            headerRange.Style.Font.Bold = true;
            for (int i = 0; i < items.Count; i++)
            {
                var row = i + 2;
                var item = items[i];
                details[$"A{row}"].Value = item.SKU;
                details[$"B{row}"].Value = item.Name;
                details[$"C{row}"].Value = item.Quantity;
                if (item.Quantity < item.ReorderLevel)
                {
                    details[$"C{row}"].Style.BackgroundColor = "#FFB6B6";
                }
            }
            using var stream = workbook.ToStream();
            return stream.ToArray();
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

IronXL handles multiple worksheets effortlessly, applies conditional formatting based on business rules, and supports advanced Excel features, such as pivot tables and charts, when needed. For detailed API documentation, visit our comprehensive reference guide.

Blazor Export to Excel: Complete Guide Using IronXL in C#: Image 3 - Advanced features example output

Conclusion

IronXL transforms Excel file generation in Blazor Server applications from a complex challenge into a straightforward task. Its intuitive API eliminates the need for Microsoft Office installations while providing access to advanced Excel features. From simple data exports to complex multi-sheet reports with formulas and formatting, IronXL handles it all with excellent performance and reliability.

Ready to enhance your Blazor applications with professional Excel export capabilities? Start your free trial of IronXL today, or explore our licensing options for production deployment.

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