Blazor Read Excel File in C# Using IronXL (Example Tutorial)

Introduction

Blazor is an open-source .NET web framework that was created by Microsoft. A Blazor application works by compiling the C# code into browser-compliant JavaScript and HTML. It doesn't require a web server to work, as it runs in a web browser. It uses the client side web platform features/details offered by WebAssembly (Blazor WASM).

In this post, I'll share knowledge about the best and easy method for reading Excel document/worksheets in Blazor serverside application using the IronXL C# library.

IronXL: .NET Excel Library

IronXL is a .NET library that allows you to treat the spreadsheet in Microsoft Excel like an object, enabling the developer to use the full power of C# and the .NET Framework to manipulate data stream. As a developer, we want a nice way through which we can get every row cells and column information from Excel document/worksheet into our applications or database. With IronXL, it is possible to get all sorts of information from a worksheet such as cell values, content of cells, images, references and formatting. IronXL is better than NPOI in many aspects. IronXL provides more functions and can make writing complex logic easier. It also has more preferable licenses and the support team is more competent.

IronXL can be used for multiple purposes such as ETL (Extract-Transform-Load), building charts or simple invoice creation in WPF, ASP.NET MVC applications, Blazor apps, and consolidating datasets with Excel pivot tables. IronXL supports all the latest versions of .NET and .NET Core frameworks.

Read Excel file in Blazor Server App

Follow the below steps to read Excel file in Blazor Server App. As the first step, we've to create a new project for Blazor Server App.

Create a Blazor Server App

Open Visual Studio 2022 and click on the "New Project" button. Search Blazor app from the project templates and hit the "Next" button. You can also choose Blazor WebAssembly app template for Blazor client side application. It's up to you how you want to read an Excel file in Blazor within a required project.

Read Excel Files in Blazor - Figure 1: Select Blazor App

Select Blazor App

Assign a suitable name to your Blazor app and hit the Next button.

Read Excel Files in Blazor - Figure 2: Create New Project

Create New Project

From the project configuration window, select the .NET framework from the list. The latest version of the .NET framework is recommended for smooth working. After selecting the .NET framework, click "Create" button. It'll create a Blazor server-side application with the required project name.

Read Excel Files in Blazor - Figure 3: Project Configuration Window

Project Configuration Window

Install IronXL library

Install the IronXL library using the NuGet Package Manager. Open the NuGet Package Manager using the top bar menu.

Read Excel Files in Blazor - Figure 4: Project Configuration Window

NuGet Package Manager

Search for the "IronXL" in the NuGet Package Manager. Select the "IronXL.Excel" library from the search results and hit the "Install" button. It'll download/import the IronXL library in the project.

Read Excel Files in Blazor - Figure 5: IronXL

IronXL

Create data files for reading Excel file

Create two classes of name "ExcelData.cs" and "ExcelDataService.cs" in the Data folder.

Read Excel Files in Blazor - Figure 6: Data files

Data files

Open the "ExcelData.cs" file and replace the code with the following code then, save the file. It'll help us to read the relevant data from the Excel document.

namespace Read_Excel.Data
{
    public class ExcelData
    {
        public string ShipMode { get; set; }

        public string Profit { get; set; }

        public string UnitPrice { get; set; }

        public string ShippingCost { get; set; }

        public string CustomerName { get; set; }
    }
}
namespace Read_Excel.Data
{
    public class ExcelData
    {
        public string ShipMode { get; set; }

        public string Profit { get; set; }

        public string UnitPrice { get; set; }

        public string ShippingCost { get; set; }

        public string CustomerName { get; set; }
    }
}
Namespace Read_Excel.Data
	Public Class ExcelData
		Public Property ShipMode() As String

		Public Property Profit() As String

		Public Property UnitPrice() As String

		Public Property ShippingCost() As String

		Public Property CustomerName() As String
	End Class
End Namespace
VB   C#

Now, open the "ExcelDataService.cs" and replace the code with the following logic. It'll help us to load and extract data from the Excel files.

using IronXL;

namespace Read_Excel.Data
{
    public class ExcelDataService
    {
        readonly List<string> sMode = new List<string>();
        readonly List<string> pAmount = new List<string>();
        readonly List<string> uPrice = new List<string>();
        readonly List<string> sCost = new List<string>();
        readonly List<string> cName = new List<string>();

        private void datafetch()
        {
            WorkBook workbook = WorkBook.Load(@"C:\Files\Data.xlsx");
            WorkSheet sheet = workbook.WorkSheets.First();
            foreach (var cell in sheet["A2:A15"])
            {
                sMode.Add(cell.Text);
            }
            foreach (var cell in sheet["B2:B15"])
            {
                pAmount.Add(cell.Text);
            }
            foreach (var cell in sheet["C2:C15"])
            {
                uPrice.Add(cell.Text);
            }
            foreach (var cell in sheet["D2:D15"])
            {
                sCost.Add(cell.Text);
            }

            foreach (var cell in sheet["E2:E15"])
            {
                cName.Add(cell.Text);
            }
        }

        public Task<ExcelData[]> GetExcelAsync()
        {
            datafetch();
            return Task.FromResult(Enumerable.Range(0, 13).Select(index => new ExcelData
            {
                ShipMode = sMode[index],
                Profit = pAmount[index],
                UnitPrice = uPrice[index],
                ShippingCost = sCost[index],
                CustomerName = cName[index]

            }).ToArray());
        }
    }
}
using IronXL;

namespace Read_Excel.Data
{
    public class ExcelDataService
    {
        readonly List<string> sMode = new List<string>();
        readonly List<string> pAmount = new List<string>();
        readonly List<string> uPrice = new List<string>();
        readonly List<string> sCost = new List<string>();
        readonly List<string> cName = new List<string>();

        private void datafetch()
        {
            WorkBook workbook = WorkBook.Load(@"C:\Files\Data.xlsx");
            WorkSheet sheet = workbook.WorkSheets.First();
            foreach (var cell in sheet["A2:A15"])
            {
                sMode.Add(cell.Text);
            }
            foreach (var cell in sheet["B2:B15"])
            {
                pAmount.Add(cell.Text);
            }
            foreach (var cell in sheet["C2:C15"])
            {
                uPrice.Add(cell.Text);
            }
            foreach (var cell in sheet["D2:D15"])
            {
                sCost.Add(cell.Text);
            }

            foreach (var cell in sheet["E2:E15"])
            {
                cName.Add(cell.Text);
            }
        }

        public Task<ExcelData[]> GetExcelAsync()
        {
            datafetch();
            return Task.FromResult(Enumerable.Range(0, 13).Select(index => new ExcelData
            {
                ShipMode = sMode[index],
                Profit = pAmount[index],
                UnitPrice = uPrice[index],
                ShippingCost = sCost[index],
                CustomerName = cName[index]

            }).ToArray());
        }
    }
}
Imports IronXL

Namespace Read_Excel.Data
	Public Class ExcelDataService
		Private ReadOnly sMode As New List(Of String)()
		Private ReadOnly pAmount As New List(Of String)()
		Private ReadOnly uPrice As New List(Of String)()
		Private ReadOnly sCost As New List(Of String)()
		Private ReadOnly cName As New List(Of String)()

		Private Sub datafetch()
			Dim workbook As WorkBook = WorkBook.Load("C:\Files\Data.xlsx")
			Dim sheet As WorkSheet = workbook.WorkSheets.First()
			For Each cell In sheet("A2:A15")
				sMode.Add(cell.Text)
			Next cell
			For Each cell In sheet("B2:B15")
				pAmount.Add(cell.Text)
			Next cell
			For Each cell In sheet("C2:C15")
				uPrice.Add(cell.Text)
			Next cell
			For Each cell In sheet("D2:D15")
				sCost.Add(cell.Text)
			Next cell

			For Each cell In sheet("E2:E15")
				cName.Add(cell.Text)
			Next cell
		End Sub

		Public Function GetExcelAsync() As Task(Of ExcelData())
			datafetch()
			Return Task.FromResult(Enumerable.Range(0, 13).Select(Function(index) New ExcelData With {
				.ShipMode = sMode(index),
				.Profit = pAmount(index),
				.UnitPrice = uPrice(index),
				.ShippingCost = sCost(index),
				.CustomerName = cName(index)
			}).ToArray())
		End Function
	End Class
End Namespace
VB   C#

In the above code, I create the list for every column of the Excel file. I load the Excel file using the "Load" function of IronXL. After loading the Excel file, I populate the string with related cell range values. I call the "datafetch()" function inside the GetExcelAsync function and convert the Excel data to an array and return it.

Excel file for reading

The following screenshot represents the Excel file that we'll read in the Blazor Server App.

Read Excel Files in Blazor - Figure 7: Excel file

Excel File

Code for displaying Excel data

Now create a Razor file of the name "ExcelDataShow.razor" inside the Pages folder.

Read Excel Files in Blazor - Figure 8: Razor files

Razor files

Add the following code in the "ExcelDataShow.razor" file.

@page "/ExcelDataShow"

<PageTitle>Excel Data</PageTitle>

@using Read_Excel.Data
@inject ExcelDataService ExcelService

<h1>Excel Data</h1>

<p>This component demonstrates fetching data from a service.</p>

@if (allData == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Ship Mode</th>
                <th>Profit</th>
                <th>Unit Price</th>
                <th>Shipping Cost</th>
                <th>Customer Name</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var data in allData)
            {
                <tr>
                    <td>@data.ShipMode</td>
                    <td>@data.Profit</td>
                    <td>@data.UnitPrice</td>
                    <td>@data.ShippingCost</td>
                    <td>@data.CustomerName</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    private ExcelData[] allData;

    protected override async Task OnInitializedAsync() => allData = await ExcelService.GetExcelAsync();
}
@page "/ExcelDataShow"

<PageTitle>Excel Data</PageTitle>

@using Read_Excel.Data
@inject ExcelDataService ExcelService

<h1>Excel Data</h1>

<p>This component demonstrates fetching data from a service.</p>

@if (allData == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Ship Mode</th>
                <th>Profit</th>
                <th>Unit Price</th>
                <th>Shipping Cost</th>
                <th>Customer Name</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var data in allData)
            {
                <tr>
                    <td>@data.ShipMode</td>
                    <td>@data.Profit</td>
                    <td>@data.UnitPrice</td>
                    <td>@data.ShippingCost</td>
                    <td>@data.CustomerName</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    private ExcelData[] allData;

    protected override async Task OnInitializedAsync() => allData = await ExcelService.GetExcelAsync();
}
'INSTANT VB TODO TASK: The following line could not be converted:
page "/ExcelDataShow" (Of PageTitle) Excel Data</PageTitle> [using] Read_Excel.Data inject ExcelDataService ExcelService (Of h1) Excel Data</h1> (Of p) This component demonstrates fetching data from a service.</p> [if](allData == Nothing)
If True Then
	(Of p)(Of em) Loading...</em></p>
Else
	<table class="table"> (Of thead) (Of tr) (Of th) Ship Mode</th> (Of th) Profit</th> (Of th) Unit Price</th> (Of th) Shipping Cost</th> (Of th) Customer Name</th> </tr> </thead> (Of tbody) foreach(var data in allData)
			If True Then
				(Of tr) (Of td) data.ShipMode</td> (Of td) data.Profit</td> (Of td) data.UnitPrice</td> (Of td) data.ShippingCost</td> (Of td) data.CustomerName</td> </tr>
			End If
		</tbody> </table>
End If

code
If True Then
	private ExcelData() allData

'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	protected override async Task OnInitializedAsync()
'	{
'		Return allData = await ExcelService.GetExcelAsync();
'	}
End If
VB   C#

In the above code, I am getting the data from the "ExcelService.cs" file using the GetExcelAsync function and using that data to populate the table.

Adding page to NavBar

Add the following code in the "NavMenu.razor" file. It'll add the nav link/url to our Excel page.

<div class="nav-item px-3">
    // comment to add link to Excel page
    <NavLink class="nav-link" href="ExcelDataShow">
        <span class="oi oi-list-rich" aria-hidden="true"></span> Excel Data
    </NavLink>
</div>
<div class="nav-item px-3">
    // comment to add link to Excel page
    <NavLink class="nav-link" href="ExcelDataShow">
        <span class="oi oi-list-rich" aria-hidden="true"></span> Excel Data
    </NavLink>
</div>
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'<div class="nav-item px-3"> <NavLink class="nav-link" href="ExcelDataShow"> <span class="oi oi-list-rich" aria-hidden="true"></span> Excel Data </NavLink> </div>
VB   C#

Adding Service to Container

Add the following code inside the "Program.cs" file. It is an important step. Don't skip it.

builder.Services.AddSingleton<ExcelDataService>();
builder.Services.AddSingleton<ExcelDataService>();
builder.Services.AddSingleton(Of ExcelDataService)()
VB   C#
Read Excel Files in Blazor - Figure 9: Adding Service

Adding Service

Run project

Now run the project. You'll see the Blazor Server App output in the browser. Click on the "Excel Data" from the navbar to read Excel file data.

Read Excel Files in Blazor - Figure 10: Blazor project

Blazor Project

Summary

In this article, I showed how easily you can read Excel files in the Blazor app using the IronXL library. IronXL allows developers to develop Excel-related applications. It provides multiple functions to manipulate or edit Excel files without installing Microsoft Excel in the system. The IronXL library is faster, is more reliable, has better documentation, and is easier to use than NPOI. It also doesn't have any bugs.

Refer to the Read Excel Files in C# Tutorial for more information about how to use IronXL, including additional links to additional articles and a YouTube video on the same topic.