Read Excel Files in ASP.NET MVC Using IronXL

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

This tutorial guides developers on implementing Excel file parsing in ASP.NET MVC apps using IronXL.

Quickstart: Load and Convert Excel Sheet to DataTable in MVC

This example shows how to get started in seconds: load an Excel workbook, pick its first worksheet, and convert it to a System.Data.DataTable using IronXL — no Interop, no hassle.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronXL with NuGet Package Manager

    PM > Install-Package IronXL.Excel

  2. Copy and run this code snippet.

    var dataTable = IronXL.WorkBook.Load("CustomerData.xlsx").DefaultWorkSheet.ToDataTable(true);
  3. Deploy to test on your live environment

    Start using IronXL in your project today with a free trial
    arrow pointer

Create an ASP.NET Project

Using Visual Studio 2022 (or similar product versions), create a new ASP.NET project. Add additional NuGet packages and source code as needed for the particular project.

Install IronXL Library

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

Primer Paso:
green arrow pointer


After creating the new project, we have to install the IronXL library. Follow the steps below to install the IronXL library. Open the NuGet Package Manager Console and run the following command:

Install-Package IronXL.Excel

Reading Excel file

Open the default controller in your ASP.NET project (e.g., HomeController.cs) and replace the Index method with the following code:

public ActionResult Index()
{
    // Load the Excel workbook from a specified path.
    WorkBook workBook = WorkBook.Load(@"C:\Files\Customer Data.xlsx");

    // Access the first worksheet from the workbook.
    WorkSheet workSheet = workBook.WorkSheets.First();

    // Convert the worksheet data to a DataTable object.
    var dataTable = workSheet.ToDataTable();

    // Send the DataTable to the view for rendering.
    return View(dataTable);
}
public ActionResult Index()
{
    // Load the Excel workbook from a specified path.
    WorkBook workBook = WorkBook.Load(@"C:\Files\Customer Data.xlsx");

    // Access the first worksheet from the workbook.
    WorkSheet workSheet = workBook.WorkSheets.First();

    // Convert the worksheet data to a DataTable object.
    var dataTable = workSheet.ToDataTable();

    // Send the DataTable to the view for rendering.
    return View(dataTable);
}
Public Function Index() As ActionResult
	' Load the Excel workbook from a specified path.
	Dim workBook As WorkBook = WorkBook.Load("C:\Files\Customer Data.xlsx")

	' Access the first worksheet from the workbook.
	Dim workSheet As WorkSheet = workBook.WorkSheets.First()

	' Convert the worksheet data to a DataTable object.
	Dim dataTable = workSheet.ToDataTable()

	' Send the DataTable to the view for rendering.
	Return View(dataTable)
End Function
$vbLabelText   $csharpLabel

In the Index action method, we load the Excel file using IronXL's Load method. The path of the Excel file (including the filename) is provided as a parameter to the method call. Next, we select the first Excel sheet as the working sheet and load the data contained in it into a DataTable object. Lastly, the DataTable is sent to the frontend.

Display Excel Data on a Web Page

The next example shows how to display the DataTable returned in the previous example in a web browser.

The working Excel file that will be used in this example is depicted below:

Read Excel Files in ASP.NET MVC Using IronXL, Figure 1: Excel file

Excel file

Open the index.cshtml (index view) and replace the code with the following HTML code.

@{
    ViewData["Title"] = "Home Page";
}

@using System.Data
@model DataTable

<div class="text-center">
    <h1 class="display-4">Welcome to IronXL Read Excel MVC</h1>
</div>
<table class="table table-dark">
    <tbody>
        @foreach (DataRow row in Model.Rows)
        {
            <tr>
                @for (int i = 0; i < Model.Columns.Count; i++)
                {
                    <td>@row[i]</td>
                }
            </tr>
        }

    </tbody>
</table>
@{
    ViewData["Title"] = "Home Page";
}

@using System.Data
@model DataTable

<div class="text-center">
    <h1 class="display-4">Welcome to IronXL Read Excel MVC</h1>
</div>
<table class="table table-dark">
    <tbody>
        @foreach (DataRow row in Model.Rows)
        {
            <tr>
                @for (int i = 0; i < Model.Columns.Count; i++)
                {
                    <td>@row[i]</td>
                }
            </tr>
        }

    </tbody>
</table>
@
If True Then
	ViewData("Title") = "Home Page"
End If

'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: using System.Data model DataTable <div class="text-center"> <h1 class="display-4"> Welcome to IronXL Read Excel MVC</h1> </div> <table class="table table-dark"> <tbody> foreach(DataRow row in Model.Rows)
"display-4"> Welcome [to] IronXL Read Excel MVC</h1> </div> <table class="table table-dark"> (Of tbody) foreach(DataRow row in Model.Rows)
		If True Then
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: using System.Data model DataTable <div class="text-center"> <h1 class="display-4"> Welcome to IronXL Read Excel MVC</h1> </div> <table class
"text-center"> <h1 class="display-4"> Welcome [to] IronXL Read Excel MVC</h1> </div> <table class
[using] System.Data model DataTable <div class="text-center"> <h1 class
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'			(Of tr) @for(int i = 0; i < Model.Columns.Count; i++)
'				{
'					<td> @row[i]</td>
'				}
			</tr>
		End If

'INSTANT VB TODO TASK: The following line uses invalid syntax:
'	</tbody> </table>
$vbLabelText   $csharpLabel

The above code uses the DataTable returned from the Index method as a model. Each row from the table is printed on the webpage using a @for loop, including Bootstrap formatting for decoration.

Running the project will produce the results shown below.

Read Excel Files in ASP.NET MVC Using IronXL, Figure 2: Bootstrap Table

Bootstrap Table

Preguntas Frecuentes

¿Cómo puedo leer archivos de Excel en ASP.NET MVC sin usar Interop?

Puede leer archivos de Excel en ASP.NET MVC sin usar Interop utilizando la biblioteca IronXL. Primero, instale IronXL a través de NuGet y luego use el método WorkBook.Load para cargar el archivo Excel. Acceda a la hoja de trabajo y conviértala a un DataTable para procesamiento adicional.

¿Qué pasos son necesarios para mostrar datos de Excel en una página web usando ASP.NET MVC?

Para mostrar datos de Excel en una página web usando ASP.NET MVC, cargue el archivo Excel con IronXL, conviértalo en un DataTable, y páselo a la vista. Use sintaxis Razor en la vista para iterar sobre el DataTable y renderizar los datos como una tabla HTML.

¿Cómo instalo la biblioteca necesaria para manejar archivos de Excel en una aplicación ASP.NET?

Para manejar archivos de Excel en una aplicación ASP.NET, instale la biblioteca IronXL abriendo la consola del Administrador de paquetes NuGet en Visual Studio y ejecutando el comando Install-Package IronXL.Excel.

¿Cuál es la ventaja de usar IronXL para operaciones de Excel en ASP.NET MVC?

IronXL simplifica las operaciones de Excel en ASP.NET MVC al proporcionar una API fácil de usar que permite leer, escribir y manipular archivos de Excel sin necesidad de Interop de Excel, mejorando así el rendimiento y reduciendo la complejidad.

¿Cómo puedo convertir una hoja de trabajo de Excel en un DataTable en ASP.NET MVC?

En ASP.NET MVC, después de cargar un archivo de Excel con IronXL, puede convertir una hoja de trabajo en un DataTable usando el método ToDataTable, lo que facilita el manejo y manipulación de datos.

¿Puede usarse IronXL en aplicaciones ASP.NET Core MVC para procesamiento de Excel?

Sí, IronXL es compatible con aplicaciones ASP.NET Core MVC y puede usarse para leer y manipular eficientemente archivos de Excel sin depender de Interop de Excel.

¿Qué modificaciones de código se requieren en el controlador para leer archivos de Excel?

Modifique el controlador predeterminado, como HomeController.cs, usando WorkBook.Load de IronXL para cargar el libro de Excel y convertir los datos de la hoja de trabajo en un DataTable para pasarlo a la vista.

¿Cómo mejora IronXL el proceso de lectura de archivos de Excel en ASP.NET?

IronXL mejora el proceso de lectura de archivos de Excel en ASP.NET al ofrecer una API sencilla que elimina la necesidad de Interop de Excel, permitiendo una lectura, escritura y manipulación sin problemas de los datos de Excel.

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