How to Export Data to Excel in Blazor Using IronXL

Introduction

Blazor is a new project released by Microsoft. It's a framework for building web apps with C# code in the browser, without a plug-in. The runtime is written in .NET, but it taps into the power of existing JavaScript frameworks that are used to develop client-side code. The Blazor framework includes Razor syntax for markup and C# for server-side code and other logic.

In this tutorial, I'll make it easy for you to export data to Excel files in Blazor app with nice presentation. I'll use the IronXL library to generate and download data in Excel files.

IronXL: C# Excel Library

IronXL is a C# Excel library designed to take care of the most time-consuming tasks in Excel, those that are repeated many times. IronXL is powerful enough to handle even the most complex problems in Excel. It can deal with huge datasets and large cells with ease which has been a difficult task for a lot of developers who use Excel for their work. The IronXL .NET library allows developers to read and write Excel files without having to use Microsoft Interop. This library helps them develop applications that can read and directly write Excel data without the need of interfacing with MS Office files or libraries on Windows platforms.

IronXL library can be used to create a variety of spreadsheets such as invoices, expense reports, or sales reports. Moreover, it can help streamline data analysis or reporting processes in your workplace by automating tasks like merging complex data sets. IronXL supports multiple file formats.

Export Data to Excel from Blazor Project

Let's follow the steps to create Excel file from Blazor Web Application.

Prerequisites

For exporting Excel files in Blazor server, there are some prerequisites:

  1. Visual Studio 2022 (Latest Version)
  2. .NET Framework 6 or 7
  3. Running Blazor server application in Visual Studio
  4. Stable Internet Connection to install IronXL library

Install IronXL library

Now, it's time to install the IronXL library. I'll install it using NuGet Package Manager Console. Open the NuGet Package Manager Console and write the following command:

Install-Package IronXL.Excel

This command will install the latest version of IronXL in the application.

Code to Download Exported Excel file

After installing IronXL, create a folder with the name "js" under the "wwwroot" section from within the Solution Explorer. In the "js" folder, create a JavaScript file with the name "SaveAsFile.js." as shown in the following screenshot.

How to Export Data to Excel in Blazor Using IronXL, Figure 1: js Folder

js Folder

Now, add the following code in the "SaveAsFile.js" file. This function will allow us to return generated files to to user as a stream.

function saveAsFile(filename, byteBase64) {
    var link = document.createElement('a');
    link.download = filename;
    link.href = "data:application/octet-stream;base64," + byteBase64;
    document.body.appendChild(link); // Needed for Firefox link
    link.click();
    document.body.removeChild(link);
}

Next, add the relative path to the "SaveAsFile.js" file in the "_Host.cshtml" file. This will allow our application to invoke the JavaScript function previously defined.

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

Code to Export Excel file

Create a class named "ExcelExport.cs" under the Data folder.

How to Export Data to Excel in Blazor Using IronXL, Figure 2: ExcelExport.cs

ExcelExport.cs

Write the following code for exporting data in the "ExcelExport.cs" file.

using IronXL;
using Microsoft.JSInterop;
using System;

namespace Export_Excel_Blazor.Data
{
    public class ExcelExport
    {
        public void ExcelGenerate(IJSRuntime iJSRuntime)
        {
            byte[] fileContents;
            WorkBook xlsxWorkbook = WorkBook.Create(IronXL.ExcelFileFormat.XLSX);
            xlsxWorkbook.Metadata.Author = "IronXL";

            //Add a blank WorkSheet
            WorkSheet xlsxSheet = xlsxWorkbook.CreateWorkSheet("new_sheet");

            //Add data and styles to the new worksheet

            xlsxSheet["A1"].Value = "Product EN";
            xlsxSheet["B1"].Value = "SKU";
            xlsxSheet["C1"].Value = "Customer";

            xlsxSheet["A1:C1"].Style.Font.Bold = true;

            xlsxSheet["A2"].Value = "Iron Rods";
            xlsxSheet["A3"].Value = "Mobile Phones";
            xlsxSheet["A4"].Value = "Chargers";

            xlsxSheet["B2"].Value = "105";
            xlsxSheet["B3"].Value = "285";
            xlsxSheet["B4"].Value = "301";

            xlsxSheet["C2"].Value = "Adam";
            xlsxSheet["C3"].Value = "Ellen";
            xlsxSheet["C4"].Value = "Tom";

            fileContents = xlsxWorkbook.ToByteArray();

            iJSRuntime.InvokeAsync<ExcelExport>(
                "saveAsFile",
                "GeneratedExcel.xlsx",
                Convert.ToBase64String(fileContents)
            );
        }
    }
}
using IronXL;
using Microsoft.JSInterop;
using System;

namespace Export_Excel_Blazor.Data
{
    public class ExcelExport
    {
        public void ExcelGenerate(IJSRuntime iJSRuntime)
        {
            byte[] fileContents;
            WorkBook xlsxWorkbook = WorkBook.Create(IronXL.ExcelFileFormat.XLSX);
            xlsxWorkbook.Metadata.Author = "IronXL";

            //Add a blank WorkSheet
            WorkSheet xlsxSheet = xlsxWorkbook.CreateWorkSheet("new_sheet");

            //Add data and styles to the new worksheet

            xlsxSheet["A1"].Value = "Product EN";
            xlsxSheet["B1"].Value = "SKU";
            xlsxSheet["C1"].Value = "Customer";

            xlsxSheet["A1:C1"].Style.Font.Bold = true;

            xlsxSheet["A2"].Value = "Iron Rods";
            xlsxSheet["A3"].Value = "Mobile Phones";
            xlsxSheet["A4"].Value = "Chargers";

            xlsxSheet["B2"].Value = "105";
            xlsxSheet["B3"].Value = "285";
            xlsxSheet["B4"].Value = "301";

            xlsxSheet["C2"].Value = "Adam";
            xlsxSheet["C3"].Value = "Ellen";
            xlsxSheet["C4"].Value = "Tom";

            fileContents = xlsxWorkbook.ToByteArray();

            iJSRuntime.InvokeAsync<ExcelExport>(
                "saveAsFile",
                "GeneratedExcel.xlsx",
                Convert.ToBase64String(fileContents)
            );
        }
    }
}
Imports IronXL
Imports Microsoft.JSInterop
Imports System

Namespace Export_Excel_Blazor.Data
	Public Class ExcelExport
		Public Sub ExcelGenerate(ByVal iJSRuntime As IJSRuntime)
			Dim fileContents() As Byte
			Dim xlsxWorkbook As WorkBook = WorkBook.Create(IronXL.ExcelFileFormat.XLSX)
			xlsxWorkbook.Metadata.Author = "IronXL"

			'Add a blank WorkSheet
			Dim xlsxSheet As WorkSheet = xlsxWorkbook.CreateWorkSheet("new_sheet")

			'Add data and styles to the new worksheet

			xlsxSheet("A1").Value = "Product EN"
			xlsxSheet("B1").Value = "SKU"
			xlsxSheet("C1").Value = "Customer"

			xlsxSheet("A1:C1").Style.Font.Bold = True

			xlsxSheet("A2").Value = "Iron Rods"
			xlsxSheet("A3").Value = "Mobile Phones"
			xlsxSheet("A4").Value = "Chargers"

			xlsxSheet("B2").Value = "105"
			xlsxSheet("B3").Value = "285"
			xlsxSheet("B4").Value = "301"

			xlsxSheet("C2").Value = "Adam"
			xlsxSheet("C3").Value = "Ellen"
			xlsxSheet("C4").Value = "Tom"

			fileContents = xlsxWorkbook.ToByteArray()

			iJSRuntime.InvokeAsync(Of ExcelExport)("saveAsFile", "GeneratedExcel.xlsx", Convert.ToBase64String(fileContents))
		End Sub
	End Class
End Namespace
VB   C#

In the above example, I use IronXL to create an Excel workbook in XLSX format. IronXL also supports the XLS format. I add a worksheet to the created workbook. After that, I fill the sheet with dummy data.

In the next step, I convert the workbook content to the byte array. Then, I invoke the IJSRuntime to download the file. In the parameter, I pass the name of the JavaScript function, the file name for the exported file, and workbook's byte array.

Create Razor Component

Create a Razor component named "ExportExcel.razor" under the Pages folder.

How to Export Data to Excel in Blazor Using IronXL, Figure 3: ExportExcel.razor

ExcelExport.cs

Next, replace the source code of ExportExcel.razor with one given below.

@page "/export"
@using Export_Excel_Blazor.Data
@inject IJSRuntime JS

<h1>IronXL Export Excel File</h1>

<p>Intuitive C# & VB.NET Excel API & No need to install MS Office or Excel Interop</p>

<button class="btn btn-primary" @onclick="ExcelGeneration">Create Excel File</button>

@code {

    private void ExcelGeneration()
    {
        ExcelExport excelExport = new ExcelExport();
        excelExport.ExcelGenerate(JS);
    }
}
@page "/export"
@using Export_Excel_Blazor.Data
@inject IJSRuntime JS

<h1>IronXL Export Excel File</h1>

<p>Intuitive C# & VB.NET Excel API & No need to install MS Office or Excel Interop</p>

<button class="btn btn-primary" @onclick="ExcelGeneration">Create Excel File</button>

@code {

    private void ExcelGeneration()
    {
        ExcelExport excelExport = new ExcelExport();
        excelExport.ExcelGenerate(JS);
    }
}
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: @page "/export" using Export_Excel_Blazor.Data inject IJSRuntime JS <h1> IronXL Export Excel File</h1> <p> Intuitive C# & VB.NET Excel API & No need to install MS Office or Excel Interop</p> <button class="btn btn-primary" onclick="ExcelGeneration"> Create Excel File</button> @code
"btn btn-primary" onclick="ExcelGeneration"> Create Excel File</button> code
Private Friend page "/export" [using] Export_Excel_Blazor.Data inject IJSRuntime JS (Of h1) IronXL Export Excel File</h1> (Of p) Intuitive C# & VB.NET Excel API And No need [to] install MS Office [or] Excel Interop</p> <button Class="btn btn-primary" onclick

	Private Sub ExcelGeneration()
		Dim excelExport As New ExcelExport()
		excelExport.ExcelGenerate(JS)
	End Sub
End Class
VB   C#

In the above HTML code, I create a button with an onclick property pointing to the "ExcelGeneration" function. Then, I write the "ExcelGeneration" function inside the @code section.

Add the following piece of code in the "NavMenu.razor" file. It'll add a nav bar menu to reach the Excel Generation page.

<li class="nav-item px-3">
    <NavLink class="nav-link" href="export">
        <span class="oi oi-list-rich" aria-hidden="true"></span> Export Excel
    </NavLink>
</li>
HTML

Run Project

Finally, run the project. You'll see the following output in the browser. Go to the "Export Excel" nav menu and click on the "Create Excel File" button.

How to Export Data to Excel in Blazor Using IronXL, Figure 4: ExportExcel.razor

ExcelExport.cs

The application will export data to Excel spreadsheet and download the XLSX file to your machine.

How to Export Data to Excel in Blazor Using IronXL, Figure 5: Download Excel

Download Excel

Generated Excel Spreadsheet

This is the preview of generated Excel file.

How to Export Data to Excel in Blazor Using IronXL, Figure 6: Generated Excel

Generated Excel

Summary

In this article, we learnt how we can generate and export Excel files in the Blazor application using IronXL. IronXL is a great tool for .NET developers who have to manipulate Excel files in the software without installing Microsoft Office on the machine. IronXL provides a much faster way to build Excel applications in .NET.

IronXL is built on top of the C# language and provides fast and easy code development for building interactive and highly responsive user interfaces in the world's most popular spreadsheet application. Microsoft Interop is a relatively slower library with more complex coding required. Microsoft Interop is slower than IronXL because it requires the use of COM for reading and writing data. Explore more articles related to IronXL using this link.