How to Export Data to Excel in Blazor using IronXL

In this tutorial, we explore exporting data in Excel using Blazor and IronXL within Visual Studio 2022. The process begins with setting up a saveAsFile.js script to create a download link for files, using a base64 byte array as input. This script is linked to the Blazor app by referencing it in the host.cshtml file. We then delve into the ExportExcel.cs file, which houses the main procedure for data conversion to Excel. Here, we define a method GenerateExcel to create and populate an Excel workbook and worksheet with sample data, headers, product names, SKUs, and customer information. Using JS interop, we call the JavaScript function to download the Excel file. The ExportExcel.razor file creates a button to trigger the GenerateExcel method, facilitated by an instance of IJSRuntime for JavaScript function invocation. Finally, the NavMenu.razor file is updated to include a navigation link to the Excel export page. Running the project allows us to generate and download an Excel file, showcasing the defined data, headers, and demonstrating IronXL's capabilities in Blazor.

Setup saveAsFile.js

// This script is responsible for converting a base64 string into a downloadable file link.
function saveAsFile(fileName, byteBase64) {
    var link = document.createElement('a'); // Create a link element
    link.download = fileName; // Set the download attribute with the filename
    link.href = "data:application/octet-stream;base64," + byteBase64; // Set the href to the base64 file data
    document.body.appendChild(link); // Append the link to the document body
    link.click(); // Programmatically click the link to trigger the download
    document.body.removeChild(link); // Remove the link from the document after download
}
// This script is responsible for converting a base64 string into a downloadable file link.
function saveAsFile(fileName, byteBase64) {
    var link = document.createElement('a'); // Create a link element
    link.download = fileName; // Set the download attribute with the filename
    link.href = "data:application/octet-stream;base64," + byteBase64; // Set the href to the base64 file data
    document.body.appendChild(link); // Append the link to the document body
    link.click(); // Programmatically click the link to trigger the download
    document.body.removeChild(link); // Remove the link from the document after download
}
JAVASCRIPT

Update host.cshtml

Reference the saveAsFile.js script within the _Host.cshtml file to ensure it is accessible from the Blazor app.

<script src="saveAsFile.js"></script>
<script src="saveAsFile.js"></script>
HTML

ExportExcel.cs

This file contains the method for generating an Excel file using IronXL.

using IronXL;
using Microsoft.JSInterop; // Required for invoking JavaScript functions

public class ExportExcel
{
    private readonly IJSRuntime _jsRuntime;

    public ExportExcel(IJSRuntime jsRuntime)
    {
        _jsRuntime = jsRuntime;
    }

    // Method to generate an Excel file and initiate its download
    public async Task GenerateExcel()
    {
        // Create a new workbook and worksheet
        var workbook = WorkBook.Create();
        var sheet = workbook.CreateWorkSheet("Sample Data");

        // Set headers
        sheet["A1"].Value = "Product Name";
        sheet["B1"].Value = "SKU";
        sheet["C1"].Value = "Customer";

        // Add sample data
        sheet["A2"].Value = "Gadget";
        sheet["B2"].Value = "001";
        sheet["C2"].Value = "John Doe";

        // Save the workbook to a byte array
        byte[] excelData = workbook.ToByteArray();

        // Convert the byte array to a Base64 string
        string excelBase64 = Convert.ToBase64String(excelData);

        // Use JSInterop to trigger file download in the browser
        await _jsRuntime.InvokeVoidAsync("saveAsFile", "SampleData.xlsx", excelBase64);
    }
}
using IronXL;
using Microsoft.JSInterop; // Required for invoking JavaScript functions

public class ExportExcel
{
    private readonly IJSRuntime _jsRuntime;

    public ExportExcel(IJSRuntime jsRuntime)
    {
        _jsRuntime = jsRuntime;
    }

    // Method to generate an Excel file and initiate its download
    public async Task GenerateExcel()
    {
        // Create a new workbook and worksheet
        var workbook = WorkBook.Create();
        var sheet = workbook.CreateWorkSheet("Sample Data");

        // Set headers
        sheet["A1"].Value = "Product Name";
        sheet["B1"].Value = "SKU";
        sheet["C1"].Value = "Customer";

        // Add sample data
        sheet["A2"].Value = "Gadget";
        sheet["B2"].Value = "001";
        sheet["C2"].Value = "John Doe";

        // Save the workbook to a byte array
        byte[] excelData = workbook.ToByteArray();

        // Convert the byte array to a Base64 string
        string excelBase64 = Convert.ToBase64String(excelData);

        // Use JSInterop to trigger file download in the browser
        await _jsRuntime.InvokeVoidAsync("saveAsFile", "SampleData.xlsx", excelBase64);
    }
}
Imports IronXL
Imports Microsoft.JSInterop ' Required for invoking JavaScript functions

Public Class ExportExcel
	Private ReadOnly _jsRuntime As IJSRuntime

	Public Sub New(ByVal jsRuntime As IJSRuntime)
		_jsRuntime = jsRuntime
	End Sub

	' Method to generate an Excel file and initiate its download
	Public Async Function GenerateExcel() As Task
		' Create a new workbook and worksheet
		Dim workbook = WorkBook.Create()
		Dim sheet = workbook.CreateWorkSheet("Sample Data")

		' Set headers
		sheet("A1").Value = "Product Name"
		sheet("B1").Value = "SKU"
		sheet("C1").Value = "Customer"

		' Add sample data
		sheet("A2").Value = "Gadget"
		sheet("B2").Value = "001"
		sheet("C2").Value = "John Doe"

		' Save the workbook to a byte array
		Dim excelData() As Byte = workbook.ToByteArray()

		' Convert the byte array to a Base64 string
		Dim excelBase64 As String = Convert.ToBase64String(excelData)

		' Use JSInterop to trigger file download in the browser
		Await _jsRuntime.InvokeVoidAsync("saveAsFile", "SampleData.xlsx", excelBase64)
	End Function
End Class
$vbLabelText   $csharpLabel

ExportExcel.razor

This file sets up a user interface to trigger the Excel export process.

@page "/exportExcel"
@inject ExportExcel exportExcel

<h3>Export to Excel</h3>
<button @onclick="exportExcel.GenerateExcel">Download Excel</button>

Update NavMenu.razor

Add a navigation link to the Excel export page for easy access.

<NavLink href="exportExcel" Match="NavLinkMatch.All">
    <span class="oi oi-spreadsheet" aria-hidden="true"></span> Export to Excel
</NavLink>

Further Reading: How to Export Data to Excel in Blazor using IronXL

Regan Pun
Software Engineer
Regan graduated from the University of Reading, with a BA in Electronic Engineering. Before joining Iron Software, his previous job roles had him laser-focused on single tasks; and what he most enjoys at Iron Software is the spectrum of work he gets to undertake, whether it’s adding value to sales, technical support, product development or marketing. He enjoys understanding the way developers are using the Iron Software library, and using that knowledge to continually improve documentation and develop the products.
< PREVIOUS
How to Import CSV To Datatable in C#
NEXT >
A Comparison of IronXL vs Spire.XLS