Skip to footer content
USING IRONXL

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.

IronXL's primary feature enables developers to create, edit, manipulate, and read Excel files without requiring Microsoft Excel. This means there's no need to install Microsoft Excel on your system. This functionality offers various possibilities for developers, simplifying the integration of Excel data within applications. For example, a developer can automatically generate reports from a database and export them to Excel for easy distribution. For a detailed guide on reading Excel files in C#, refer to this C# Read Excel file tutorial.

using IronXL;

class Program
{
    static void Main()
    {
        // Set the license key for IronXL
        License.LicenseKey = "Your-License-Key"; // Ensure the correct license key is set

        // Load an existing Excel file
        WorkBook workbook = WorkBook.Load("ExistingData.xlsx");
        WorkSheet sheet = workbook.DefaultWorkSheet;

        // For example, changing the sales value in cell C2
        if (!sheet["C2"].IsEmpty)
        {
            double currentSales = sheet["C2"].DoubleValue;
            // Increase sales by 10%
            sheet["C2"].Value = currentSales * 1.10;
        }

        // Save the changes back to the same file or a new file
        workbook.SaveAs("UpdatedData.xlsx");
    }
}
using IronXL;

class Program
{
    static void Main()
    {
        // Set the license key for IronXL
        License.LicenseKey = "Your-License-Key"; // Ensure the correct license key is set

        // Load an existing Excel file
        WorkBook workbook = WorkBook.Load("ExistingData.xlsx");
        WorkSheet sheet = workbook.DefaultWorkSheet;

        // For example, changing the sales value in cell C2
        if (!sheet["C2"].IsEmpty)
        {
            double currentSales = sheet["C2"].DoubleValue;
            // Increase sales by 10%
            sheet["C2"].Value = currentSales * 1.10;
        }

        // Save the changes back to the same file or a new file
        workbook.SaveAs("UpdatedData.xlsx");
    }
}
Imports IronXL

Friend Class Program
	Shared Sub Main()
		' Set the license key for IronXL
		License.LicenseKey = "Your-License-Key" ' Ensure the correct license key is set

		' Load an existing Excel file
		Dim workbook As WorkBook = WorkBook.Load("ExistingData.xlsx")
		Dim sheet As WorkSheet = workbook.DefaultWorkSheet

		' For example, changing the sales value in cell C2
		If Not sheet("C2").IsEmpty Then
			Dim currentSales As Double = sheet("C2").DoubleValue
			' Increase sales by 10%
			sheet("C2").Value = currentSales * 1.10
		End If

		' Save the changes back to the same file or a new file
		workbook.SaveAs("UpdatedData.xlsx")
	End Sub
End Class
$vbLabelText   $csharpLabel

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 will return 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);
}
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();

            // Trigger JavaScript function to download the file
            iJSRuntime.InvokeAsync<object>(
                "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();

            // Trigger JavaScript function to download the file
            iJSRuntime.InvokeAsync<object>(
                "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()

			' Trigger JavaScript function to download the file
			iJSRuntime.InvokeAsync(Of Object)("saveAsFile", "GeneratedExcel.xlsx", Convert.ToBase64String(fileContents))
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

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 triggered 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: ExportExcel.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);
    }
}

In the above HTML code, create a button with an 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.

Frequently Asked Questions

How can I export data to Excel in a Blazor Web Application?

To export data to Excel in a Blazor Web Application using IronXL, you need to set up a Blazor project, install the IronXL library via NuGet, create an Excel workbook and fill it with data using IronXL's APIs, and then convert the workbook to a Byte Array for downloading through JavaScript.

What are the prerequisites for exporting Excel files in a Blazor Server Application?

The prerequisites include having Visual Studio, .NET Framework 6 or 7, a running Blazor Server Application, and a stable internet connection to install the IronXL library through NuGet.

Why use IronXL for Excel file manipulation in Blazor applications?

IronXL simplifies Excel file manipulation by providing a C# library that allows developers to create, edit, and read Excel files without needing Microsoft Excel. It offers a faster alternative to Microsoft Interop by eliminating the complexities associated with COM dependencies.

How do you install IronXL in a Blazor project?

IronXL can be installed in a Blazor project using the NuGet Package Manager Console in Visual Studio with the following command: Install-Package IronXL.Excel.

What role does JavaScript play in exporting Excel files in Blazor?

JavaScript is used to download the generated Excel file by converting the workbook's Byte Array into a Base64 string and invoking a JavaScript function to save the file on the user's machine.

Can IronXL handle large datasets and complex Excel operations?

Yes, IronXL is designed to handle large datasets and complex Excel operations efficiently, making it suitable for applications that require extensive data manipulation and analysis.

Is Microsoft Excel needed to work with IronXL?

No, you do not need Microsoft Excel installed to use IronXL. It enables creating and manipulating Excel files independently of Microsoft Office, streamlining the development process.

What are some applications that benefit from using IronXL?

Applications that require generating reports, invoices, or handling extensive sales data can benefit from IronXL, as it automates data manipulation tasks, making data analysis and reporting more efficient.

How does IronXL compare to Microsoft Interop for Excel manipulation?

IronXL is a faster and more straightforward solution compared to Microsoft Interop, as it does not rely on COM for data operations and does not require the installation of Microsoft Office, making it more efficient for development.

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 ...Read More