Cómo leer un archivo de Excel en Blazor usando C#

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

This article was translated from English: Does it need improvement?
Translated
View the article in English

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. In this tutorial, I'll share knowledge about the best and easy method for reading Excel documents/worksheets in a Blazor server-side application using the IronXL C# library.

Demonstration of IronXL Viewing Excel in Blazor

Get started with IronXL

Comience a usar IronXL en su proyecto hoy con una prueba gratuita.

Primer Paso:
green arrow pointer


Step 1 - Create a Blazor Project in Visual Studio

I have an XLSX file containing the following data that I will read into and open in the Blazor Server App:

Input XLSX Excel Sheet Result in Blazor Server Browser
First name Last name ID
John Applesmith 1
Richard Smith 2
Sherry Robins 3
Browser View related to Step 1 - Create a Blazor Project in Visual Studio

Start off by creating a Blazor Project from the Visual Studio IDE:

New Project related to Step 1 - Create a Blazor Project in Visual Studio

Choose the Blazor Server App Project type:

Choose Blazor Project Type related to Step 1 - Create a Blazor Project in Visual Studio

Go ahead and run the Application without changing the solution with the F5 key. Navigate to the Fetch data tab of the Application like so:

First Run related to Step 1 - Create a Blazor Project in Visual Studio

Our goal will be to load our Excel file into the Blazor app with an upload button and then display it on this page.

Step 2 - Add IronXL to your Solution

IronXL: .NET Excel Library (Installation Instructions):

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 streams. As a developer, we want a nice way through which we can get every row's cells and column information from Excel documents/worksheets into our applications or databases.

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 supports all the latest versions of .NET (8, 7, and 6) and .NET Core Framework 4.6.2+.

Add IronXL to your solution using one of the methods below then build the solution.

Option 2A - Use NuGet Package Manager

Install-Package IronXL.Excel

Option 2B - Add PackageReference in the csproj file

You can add IronXL directly to your project by adding the following line to any <ItemGroup> in the .csproj file of your solution:

<PackageReference Include="IronXL.Excel" Version="*" />
<PackageReference Include="IronXL.Excel" Version="*" />
XML

As shown here in Visual Studio:

Add Ironxl Csproj related to Option 2B - Add PackageReference in the csproj file

Step 3 - Coding the File Upload and View

In the Visual Studio Solution View, go to the Pages/ folder and find the FetchData.razor file. You may use any other razor file but we will use this one because it comes with the Blazor Server App Template.

Replace the file contents with the following code:

@using IronXL;
@using System.Data;

@page "/fetchdata"

<PageTitle>Excel File Viewer</PageTitle>

<h1>Open Excel File to View</h1>

<InputFile OnChange="@OpenExcelFileFromDisk" />

<table>
    <thead>
        <tr>
            @foreach (DataColumn column in displayDataTable.Columns)
            {
                <th>
                    @column.ColumnName
                </th>
            }
        </tr>
    </thead>
    <tbody>
        @foreach (DataRow row in displayDataTable.Rows)
        {
            <tr>
                @foreach (DataColumn column in displayDataTable.Columns)
                {
                    <td>
                        @row[column.ColumnName].ToString()
                    </td>
                }
            </tr>
        }
    </tbody>
</table>

@code {
    // Create a DataTable instance
    private DataTable displayDataTable = new DataTable();

    // This method is triggered when a file is uploaded
    async Task OpenExcelFileFromDisk(InputFileChangeEventArgs e)
    {
        IronXL.License.LicenseKey = "PASTE TRIAL OR LICENSE KEY";

        // Load the uploaded file into a MemoryStream
        MemoryStream ms = new MemoryStream();

        await e.File.OpenReadStream().CopyToAsync(ms);
        ms.Position = 0;

        // Create an IronXL workbook from the MemoryStream
        WorkBook loadedWorkBook = WorkBook.FromStream(ms);
        WorkSheet loadedWorkSheet = loadedWorkBook.DefaultWorkSheet; // Or use .GetWorkSheet()

        // Add header Columns to the DataTable
        RangeRow headerRow = loadedWorkSheet.GetRow(0);
        for (int col = 0; col < loadedWorkSheet.ColumnCount; col++)
        {
            displayDataTable.Columns.Add(headerRow.ElementAt(col).ToString());
        }

        // Populate the DataTable with data from the Excel sheet
        for (int row = 1; row < loadedWorkSheet.RowCount; row++)
        {
            IEnumerable<string> excelRow = loadedWorkSheet.GetRow(row).ToArray().Select(c => c.ToString());
            displayDataTable.Rows.Add(excelRow.ToArray());
        }
    }
}
@using IronXL;
@using System.Data;

@page "/fetchdata"

<PageTitle>Excel File Viewer</PageTitle>

<h1>Open Excel File to View</h1>

<InputFile OnChange="@OpenExcelFileFromDisk" />

<table>
    <thead>
        <tr>
            @foreach (DataColumn column in displayDataTable.Columns)
            {
                <th>
                    @column.ColumnName
                </th>
            }
        </tr>
    </thead>
    <tbody>
        @foreach (DataRow row in displayDataTable.Rows)
        {
            <tr>
                @foreach (DataColumn column in displayDataTable.Columns)
                {
                    <td>
                        @row[column.ColumnName].ToString()
                    </td>
                }
            </tr>
        }
    </tbody>
</table>

@code {
    // Create a DataTable instance
    private DataTable displayDataTable = new DataTable();

    // This method is triggered when a file is uploaded
    async Task OpenExcelFileFromDisk(InputFileChangeEventArgs e)
    {
        IronXL.License.LicenseKey = "PASTE TRIAL OR LICENSE KEY";

        // Load the uploaded file into a MemoryStream
        MemoryStream ms = new MemoryStream();

        await e.File.OpenReadStream().CopyToAsync(ms);
        ms.Position = 0;

        // Create an IronXL workbook from the MemoryStream
        WorkBook loadedWorkBook = WorkBook.FromStream(ms);
        WorkSheet loadedWorkSheet = loadedWorkBook.DefaultWorkSheet; // Or use .GetWorkSheet()

        // Add header Columns to the DataTable
        RangeRow headerRow = loadedWorkSheet.GetRow(0);
        for (int col = 0; col < loadedWorkSheet.ColumnCount; col++)
        {
            displayDataTable.Columns.Add(headerRow.ElementAt(col).ToString());
        }

        // Populate the DataTable with data from the Excel sheet
        for (int row = 1; row < loadedWorkSheet.RowCount; row++)
        {
            IEnumerable<string> excelRow = loadedWorkSheet.GetRow(row).ToArray().Select(c => c.ToString());
            displayDataTable.Rows.Add(excelRow.ToArray());
        }
    }
}
Private IronXL As [using]
Private System As [using]

'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'@page "/fetchdata" (Of PageTitle) Excel File Viewer</PageTitle> (Of h1) Open Excel File @to View</h1> <InputFile OnChange="@OpenExcelFileFromDisk" /> (Of table) (Of thead) (Of tr) @foreach(DataColumn column in displayDataTable.Columns)
'			{
'				<th> @column.ColumnName </th>
'			}
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'		</tr> </thead> (Of tbody) @foreach(DataRow row in displayDataTable.Rows)
'		{
'			<tr> @foreach(DataColumn column in displayDataTable.Columns)
'				{
'					<td> @row[column.ColumnName].ToString() </td>
'				}
'			</tr>
'		}
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	</tbody> </table> @code
'	{
'	' Create a DataTable instance
'	private DataTable displayDataTable = New DataTable();
'
'	' This method is triggered when a file is uploaded
'	async Task OpenExcelFileFromDisk(InputFileChangeEventArgs e)
'	{
'		IronXL.License.LicenseKey = "PASTE TRIAL OR LICENSE KEY";
'
'		' Load the uploaded file into a MemoryStream
'		MemoryStream ms = New MemoryStream();
'
'		await e.File.OpenReadStream().CopyToAsync(ms);
'		ms.Position = 0;
'
'		' Create an IronXL workbook from the MemoryStream
'		WorkBook loadedWorkBook = WorkBook.FromStream(ms);
'		WorkSheet loadedWorkSheet = loadedWorkBook.DefaultWorkSheet; ' Or use .GetWorkSheet()
'
'		' Add header Columns to the DataTable
'		RangeRow headerRow = loadedWorkSheet.GetRow(0);
'		for (int col = 0; col < loadedWorkSheet.ColumnCount; col++)
'		{
'			displayDataTable.Columns.Add(headerRow.ElementAt(col).ToString());
'		}
'
'		' Populate the DataTable with data from the Excel sheet
'		for (int row = 1; row < loadedWorkSheet.RowCount; row++)
'		{
'			IEnumerable<string> excelRow = loadedWorkSheet.GetRow(row).ToArray().@Select(c => c.ToString());
'			displayDataTable.Rows.Add(excelRow.ToArray());
'		}
'	}
'}
$vbLabelText   $csharpLabel

Summary

The <InputFile> component allows you to upload a file on this webpage. We have set the invoked event callback to call OpenExcelFileFromDisk, which is the async method in the @code block at the bottom. The HTML will render your Excel sheet as a table on the tab.

IronXL.Excel is a standalone .NET software library for reading a wide variety of spreadsheet formats. It does not require Microsoft Excel to be installed, and is not dependent on Interop.


Further Reading

Documentation related to Further Reading

View the API Reference

Explore the API Reference for IronXL, outlining the details of all of IronXL’s features, namespaces, classes, methods fields and enums.

View the API Reference

Download the software product.

Preguntas Frecuentes

¿Cómo puedo leer archivos de Excel en una aplicación del lado del servidor Blazor?

Para leer archivos de Excel en una aplicación del lado del servidor Blazor, puede usar la biblioteca de C# IronXL. Le permite integrarse fácilmente con su proyecto Blazor utilizando el Administrador de Paquetes NuGet para instalar la biblioteca y luego implementar el código para leer y mostrar los datos de Excel.

¿Cuáles son los pasos para configurar un proyecto Blazor para leer archivos de Excel?

Primero, instale IronXL a través del Administrador de Paquetes NuGet. Luego, cree un botón de carga de archivos en su aplicación Blazor. Use IronXL para leer el archivo de Excel cargado y configure la aplicación para mostrar los datos en una tabla utilizando componentes Razor.

¿Es posible leer archivos de Excel en una aplicación Blazor sin tener Excel instalado?

Sí, con IronXL, puede leer y manipular archivos de Excel en una aplicación Blazor sin tener Microsoft Excel instalado en su sistema.

¿Cómo puedo mostrar datos de Excel en una aplicación Blazor?

Después de leer el archivo de Excel usando IronXL, puede usar componentes Razor en su aplicación Blazor para mostrar los datos en formato de tabla, mejorando la interfaz de usuario.

¿Qué beneficios ofrece IronXL sobre otras bibliotecas de Excel?

IronXL proporciona una amplia funcionalidad, facilidad para manejar lógica compleja, términos de licencia superiores, y soporte dedicado, lo que lo convierte en una opción preferible sobre alternativas como NPOI.

¿Qué versiones de .NET son compatibles con IronXL para la manipulación de Excel?

IronXL es compatible con todas las versiones más recientes de .NET, incluyendo 8, 7 y 6, así como el Marco de .NET Core 4.6.2+, asegurando una amplia compatibilidad con aplicaciones modernas.

¿Cómo integro una biblioteca de Excel en mi proyecto Blazor?

Puede integrar una biblioteca de Excel como IronXL en su proyecto Blazor utilizando el Administrador de Paquetes NuGet con el comando dotnet add package IronXL.Excel o agregando una PackageReference en el archivo .csproj.

¿Qué pasos de solución de problemas puedo tomar si mi aplicación Blazor no lee un archivo de Excel?

Asegúrese de que IronXL esté correctamente instalado a través de NuGet y que su aplicación Blazor tenga los permisos necesarios para leer archivos desde el disco. Verifique que la ruta del archivo de Excel sea correcta y que el formato de archivo sea compatible con IronXL.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 1,686,155 | Versión: 2025.11 recién lanzado