How to Export Data to Excel in Blazor Using IronXL

This tutorial will explain how to export data to Excel files in a Blazor Web Application with an appealing presentation, using 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. This library helps them develop applications that can read and directly write Excel data without the need to interface with Microsoft Office files or libraries on Windows.

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 an Excel file from a Blazor Web Application.

Prerequisites

For exporting Excel files in a Blazor Server Application, there are some prerequisites:

  1. Visual Studio (the 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 using the 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 willreturn generated files to users 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);
}
JAVASCRIPT

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

 <script src="~/js/SaveAsFile.js"></script>
 <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, the IronXL library creates an Excel WorkBook in XLSX format. IronXL also supports the XLS format. A WorkBook is necessary to have a WorkSheet added. The next step is to fill this sheet with dummy data.

After that, the whole WorkBook content is converted to the byte array and IJSRuntime is triggred to download the file with the following parameters: 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: ExcelExport.cs

Next, replace the source code of "ExportExcel.razor" with the 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, create a button with a onclick property pointing to the ExcelGeneration function. Then, the ExcelGeneration function inside the @code section is added with C# code to handle the export function.

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>
<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 ExportExcel.razor

The application will export data to an 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 the generated Excel file.

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

Summary

This article went through the process of generating and exporting 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 files 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 on how to export Excel files, control the way that cells are displayed in an Excel workbook with gridlines, chart management, and text alignment, font size, color.