Saltar al pie de página
USANDO IRONXL

Cómo ver Excel en ASP.NET

This comprehensive tutorial will demonstrate how to build an Excel viewer using ASP.NET MVC and IronXL. This viewer will enable users to display, edit, and navigate through Excel files directly from their web page.

What is IronXL?

IronXL is a powerful .NET library that provides a plethora of functionalities related to Excel operations. It offers a simplified API that lets .NET developers write, manipulate, and read Excel documents in various file formats including XLS, XLSX, CSV, and more.

With IronXL, you can read Excel files, extract data, add or edit worksheets, create or modify rows and columns, apply formulas, save changes, and so much more. All of these operations can be performed without the need for Microsoft Excel to be installed on your machine.

IronXL supports images, styling, conditional formatting, and other complex Excel features, making it a comprehensive solution for .NET Excel operations. It's perfect for handling data source and spreadsheet requirements for your ASP.NET MVC applications. The IronXL library will be used to view Excel files in ASP.NET Web Applications.

Prerequisites

  • Basic understanding of ASP.NET MVC
  • Visual Studio installed on your machine
  • Installed the IronXL library. You can find the installation guide on their official documentation.

Getting Started

First, let's create a new ASP.NET MVC project in Visual Studio.

  1. Open Visual Studio.
  2. Click File > New > Project.
  3. In the new project window, choose ASP.NET Web Application (.NET Framework) template.

    How to View Excel in ASP.NET, Figure 1: Create a new ASP.NET Web Application in Visual Studio Create a new ASP.NET Web Application in Visual Studio

  4. Name your project ExcelViewer, select the project location, and click the Create button.

    How to View Excel in ASP.NET, Figure 2: Configure your project Configure your project

This article will focus on implementing the Excel viewer functionality in this ASP.NET MVC application.

Adding IronXL to Your Project

To handle Excel file formats (like .xls, .xlsx, and .csv), IronXL offers comprehensive features to load Excel documents, read, write, and even modify Excel data. It supports formulas, images, formatting, and much more.

  1. Right-click your project in Solution Explorer, and navigate to Manage NuGet Packages.
  2. In the NuGet Package Manager, search for IronXL.Excel.
  3. Click on Install to add it to your project.

    How to View Excel in ASP.NET, Figure 3: Search and install the IronXL package in NuGet Package Manager UI Search and install the IronXL package in NuGet Package Manager UI

You can also install IronXL using the Package Manager Console with the following command:

Install-Package IronXL.Excel

How to View Excel in ASP.NET, Figure 4: Install the IronXL package from the Package Manager Console Install the IronXL package from the Package Manager Console

Now that IronXL is installed, let's move on to the next step.

Building Models

ExcelModel

The first step is to create a model for the Excel data. The ExcelModel class will represent a single Excel sheet and will contain the sheet name and the data present in the Excel sheet.

namespace Excel_File_Viewer_IronXL.Models
{
    public class ExcelModel
    {
        public string SheetName { get; set; }

        // Data is a list of string arrays, each array represents a row in the sheet.
        public List<string[]> Data { get; set; }
    }
}
namespace Excel_File_Viewer_IronXL.Models
{
    public class ExcelModel
    {
        public string SheetName { get; set; }

        // Data is a list of string arrays, each array represents a row in the sheet.
        public List<string[]> Data { get; set; }
    }
}
Namespace Excel_File_Viewer_IronXL.Models
	Public Class ExcelModel
		Public Property SheetName() As String

		' Data is a list of string arrays, each array represents a row in the sheet.
		Public Property Data() As List(Of String())
	End Class
End Namespace
$vbLabelText   $csharpLabel

The ExcelModel is defined with two properties, SheetName and Data. SheetName is a simple string to hold the name of each Excel sheet. Data is a List of string arrays to store the data of each row in the Excel sheet.

ExcelViewModel

Next, let's create ExcelViewModel. This model is a wrapper that contains a file, a message, and a list of ExcelModel which represents data from all sheets in the file.

using Microsoft.AspNetCore.Http;
using System.Collections.Generic;

namespace Excel_File_Viewer_IronXL.Models
{
    public class ExcelViewModel
    {
        public IFormFile File { get; set; }  // For uploading Excel file
        public string Message { get; set; }  // Message for storing success/error messages
        public List<ExcelModel> ExcelData { get; set; }  // List to store data from all sheets
    }
}
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;

namespace Excel_File_Viewer_IronXL.Models
{
    public class ExcelViewModel
    {
        public IFormFile File { get; set; }  // For uploading Excel file
        public string Message { get; set; }  // Message for storing success/error messages
        public List<ExcelModel> ExcelData { get; set; }  // List to store data from all sheets
    }
}
Imports Microsoft.AspNetCore.Http
Imports System.Collections.Generic

Namespace Excel_File_Viewer_IronXL.Models
	Public Class ExcelViewModel
		Public Property File() As IFormFile ' -  For uploading Excel file
		Public Property Message() As String ' -  Message for storing success/error messages
		Public Property ExcelData() As List(Of ExcelModel) ' -  List to store data from all sheets
	End Class
End Namespace
$vbLabelText   $csharpLabel

This class will be used as the view model. It has an IFormFile property for file upload, a Message string for displaying any messages, and a List<ExcelModel> to store the Excel data retrieved.

5. Create ExcelController to load Excel files for data extraction

Then create a new ExcelController. This is where the magic happens! The Excel files are loaded using IronXL's WorkBook.Load function, loop through the worksheets, extract the data, and add it to the ExcelViewModel.

using Excel_File_Viewer_IronXL.Models;
using IronXL;
using System.Collections.Generic;
using System.Web.Mvc;
using System;
using System.Linq;

public class ExcelController : Controller
{
    // GET: Excel
    public ActionResult Index()
    {
        var model = new ExcelViewModel();

        // Define the file path for the Excel file
        string filePath = Server.MapPath("~/App_Data/Test.xlsx"); 

        // List to store data for each sheet
        List<ExcelModel> data = new List<ExcelModel>();

        try
        {
            // Load workbook directly from a file path
            var workbook = WorkBook.Load(filePath);

            // Loop through all worksheets in the workbook
            foreach (var worksheet in workbook.WorkSheets)
            {
                // Add each worksheet's name and data to the data list
                data.Add(new ExcelModel
                {
                    SheetName = worksheet.Name,
                    Data = worksheet.Rows.Select(r => r.ToArray().Select(c => c.Value.ToString()).ToArray()).ToList()
                });
            }

            model.ExcelData = data;
            model.Message = "File processed successfully!";
        }
        catch (Exception ex)
        {
            model.Message = $"Error occurred while processing file: {ex.Message}";
        }

        return View(model);
    }
}
using Excel_File_Viewer_IronXL.Models;
using IronXL;
using System.Collections.Generic;
using System.Web.Mvc;
using System;
using System.Linq;

public class ExcelController : Controller
{
    // GET: Excel
    public ActionResult Index()
    {
        var model = new ExcelViewModel();

        // Define the file path for the Excel file
        string filePath = Server.MapPath("~/App_Data/Test.xlsx"); 

        // List to store data for each sheet
        List<ExcelModel> data = new List<ExcelModel>();

        try
        {
            // Load workbook directly from a file path
            var workbook = WorkBook.Load(filePath);

            // Loop through all worksheets in the workbook
            foreach (var worksheet in workbook.WorkSheets)
            {
                // Add each worksheet's name and data to the data list
                data.Add(new ExcelModel
                {
                    SheetName = worksheet.Name,
                    Data = worksheet.Rows.Select(r => r.ToArray().Select(c => c.Value.ToString()).ToArray()).ToList()
                });
            }

            model.ExcelData = data;
            model.Message = "File processed successfully!";
        }
        catch (Exception ex)
        {
            model.Message = $"Error occurred while processing file: {ex.Message}";
        }

        return View(model);
    }
}
Imports Excel_File_Viewer_IronXL.Models
Imports IronXL
Imports System.Collections.Generic
Imports System.Web.Mvc
Imports System
Imports System.Linq

Public Class ExcelController
	Inherits Controller

	' GET: Excel
	Public Function Index() As ActionResult
		Dim model = New ExcelViewModel()

		' Define the file path for the Excel file
		Dim filePath As String = Server.MapPath("~/App_Data/Test.xlsx")

		' List to store data for each sheet
		Dim data As New List(Of ExcelModel)()

		Try
			' Load workbook directly from a file path
			Dim workbook = WorkBook.Load(filePath)

			' Loop through all worksheets in the workbook
			For Each worksheet In workbook.WorkSheets
				' Add each worksheet's name and data to the data list
				data.Add(New ExcelModel With {
					.SheetName = worksheet.Name,
					.Data = worksheet.Rows.Select(Function(r) r.ToArray().Select(Function(c) c.Value.ToString()).ToArray()).ToList()
				})
			Next worksheet

			model.ExcelData = data
			model.Message = "File processed successfully!"
		Catch ex As Exception
			model.Message = $"Error occurred while processing file: {ex.Message}"
		End Try

		Return View(model)
	End Function
End Class
$vbLabelText   $csharpLabel

Here, initialize an ExcelViewModel and then load the WorkBook using IronXL, loop through each WorkSheet, and for each WorkSheet, we create an ExcelModel with the name and data of the worksheet. The ExcelModel is then added to the ExcelData list in the ExcelViewModel.

The following Excel file's data is going to be loaded and displayed:

How to View Excel in ASP.NET, Figure 5: The sample Excel file The sample Excel file

6. Create the View

In your Views/Excel directory, create a new HTML file Index.cshtml to display Excel data. Then use Bootstrap's nav-tabs to represent each sheet in the Excel file. Each sheet will be a separate tab, and the tab's content will be the sheet's data.

@model Excel_File_Viewer_IronXL.Models.ExcelViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Excel File Viewer</h2>

@if (Model.ExcelData != null)
{
    <ul class="nav nav-tabs" id="myTab" role="tablist">
        @for (int i = 0; i < Model.ExcelData.Count; i++)
        {
            <li class="nav-item">
                <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle="tab" href="#content-@i" role="tab" aria-controls="content-@i" aria-selected="@(i == 0)">
                    @Model.ExcelData[i].SheetName
                </a>
            </li>
        }
    </ul>
    <div class="tab-content" id="myTabContent">
        @for (int i = 0; i < Model.ExcelData.Count; i++)
        {
            <div class="tab-pane fade @(i == 0 ? "show active" : "")" id="content-@i" role="tabpanel" aria-labelledby="tab-@i">
                <table class="table table-bordered">
                    @foreach (var row in Model.ExcelData[i].Data)
                    {
                        <tr>
                            @foreach (var cell in row)
                            {
                                <td>@cell</td>
                            }
                        </tr>
                    }
                </table>
            </div>
        }
    </div>
}
@model Excel_File_Viewer_IronXL.Models.ExcelViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Excel File Viewer</h2>

@if (Model.ExcelData != null)
{
    <ul class="nav nav-tabs" id="myTab" role="tablist">
        @for (int i = 0; i < Model.ExcelData.Count; i++)
        {
            <li class="nav-item">
                <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle="tab" href="#content-@i" role="tab" aria-controls="content-@i" aria-selected="@(i == 0)">
                    @Model.ExcelData[i].SheetName
                </a>
            </li>
        }
    </ul>
    <div class="tab-content" id="myTabContent">
        @for (int i = 0; i < Model.ExcelData.Count; i++)
        {
            <div class="tab-pane fade @(i == 0 ? "show active" : "")" id="content-@i" role="tabpanel" aria-labelledby="tab-@i">
                <table class="table table-bordered">
                    @foreach (var row in Model.ExcelData[i].Data)
                    {
                        <tr>
                            @foreach (var cell in row)
                            {
                                <td>@cell</td>
                            }
                        </tr>
                    }
                </table>
            </div>
        }
    </div>
}
model ReadOnly Property () As Excel_File_Viewer_IronXL.Models.ExcelViewModel
	ViewBag.Title = "Index"
End Property

'INSTANT VB TODO TASK: The following line could not be converted:
(Of h2) Excel File Viewer</h2> [if](Model.ExcelData != Nothing)
If True Then
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <ul class="nav nav-tabs" id="myTab" role="tablist"> for(int i = 0; i < Model.ExcelData.Count; i++)
	"myTab" role="tablist"> [for](Integer i = 0; i < Model.ExcelData.Count; i)
		If True Then
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <ul class="nav nav-tabs" id="myTab" role
	"nav nav-tabs" id="myTab" role
	<ul class="nav nav-tabs" id
	i += 1
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <li class="nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle="tab" href="#content-@i" role="tab" aria-controls="content-@i" aria-selected="@(i == 0)"> @Model.ExcelData[i].SheetName </a> </li>
			"content-@i" aria-selected="@(i == 0)"> Model.ExcelData(i).SheetName </a> </li>
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <li class="nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle="tab" href="#content-@i" role="tab" aria-controls="content-@i" aria-selected
			"tab" aria-controls="content-@i" aria-selected
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <li class="nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle="tab" href="#content-@i" role="tab" aria-controls
			"#content-@i" role="tab" aria-controls
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <li class="nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle="tab" href="#content-@i" role
			"tab" href="#content-@i" role
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <li class="nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle="tab" href
			"tab-@i" data-toggle="tab" href
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <li class="nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle
			"nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <li class="nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id
			"nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id
			<li class="nav-item"> <a class
		End If
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: </ul> <div class="tab-content" id="myTabContent"> for(int i = 0; i < Model.ExcelData.Count; i++)
	"tab-content" id="myTabContent"> [for](Integer i = 0; i < Model.ExcelData.Count; i)
		If True Then
	</ul> <div class="tab-content" id
	i += 1
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <div class="tab-pane fade @(i == 0 ? "show active" : "")" id="content-@i" role="tabpanel" aria-labelledby="tab-@i"> <table class="table table-bordered"> foreach(var row in Model.ExcelData[i].Data)
			"tab-@i"> <table class="table table-bordered"> foreach(var row in Model.ExcelData(i).Data)
					If True Then
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <div class="tab-pane fade @(i == 0 ? "show active" : "")" id="content-@i" role="tabpanel" aria-labelledby="tab-@i"> <table class
			"tabpanel" aria-labelledby="tab-@i"> <table class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <div class="tab-pane fade @(i == 0 ? "show active" : "")" id="content-@i" role="tabpanel" aria-labelledby
			"content-@i" role="tabpanel" aria-labelledby
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <div class="tab-pane fade @(i == 0 ? "show active" : "")" id="content-@i" role
			"tab-pane fade @(i == 0 ? "show active" : "")" id="content-@i" role
			<div class="tab-pane fade @(i == 0 ? "show active" : "")" id
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'						(Of tr) @foreach(var cell in row)
'							{
'								<td> @cell</td>
'							}
						</tr>
					End If
				</table> </div>
		End If
	</div>
End If
$vbLabelText   $csharpLabel

In this code example, nav nav-tabs will generate a list of tabs, each representing a sheet from the Excel file. The corresponding tab content will display the data of the respective sheet in a table format. By making some changes, a browse button is added to select the Excel file manually.

Running the Program

After you have followed all the steps and set up the project correctly, it's time to run it. You should see a web page with tabs named after the sheet names in your Excel file. Clicking on a tab will display the respective sheet's data in a table format.

How to View Excel in ASP.NET, Figure 6: The Excel Viewer The Excel Viewer

Conclusion

You've just created an ASP.NET Excel viewer using IronXL! This powerful library enables users to work with Excel files in a more efficient and manageable way. With the help of IronXL, dealing with Excel files has never been easier in the .NET environment.

IronXL provides a free trial, allowing you to explore and understand its vast functionality without any upfront cost. Once you've tested it and found it to be the perfect solution for your needs, the license starts from $799.

Preguntas Frecuentes

¿Cómo puedo crear un visor de Excel usando ASP.NET MVC?

Puedes crear un visor de Excel usando ASP.NET MVC configurando un nuevo proyecto en Visual Studio y añadiendo la biblioteca IronXL a través del Administrador de Paquetes NuGet. Esto te permite cargar, mostrar y manipular archivos de Excel directamente en tu aplicación web.

¿Cuáles son los pasos para configurar un proyecto ASP.NET MVC para manejar archivos de Excel?

Para configurar un proyecto ASP.NET MVC para manejar archivos de Excel, abre Visual Studio, crea un nuevo proyecto de Aplicación Web ASP.NET e instala la biblioteca IronXL vía NuGet. Luego, implementa modelos como ExcelModel y ExcelViewModel para gestionar datos de Excel y usa el ExcelController para cargar y procesar archivos de Excel.

¿Puedo mostrar múltiples hojas de Excel en una aplicación ASP.NET?

Sí, puedes mostrar múltiples hojas de Excel en una aplicación ASP.NET usando IronXL para cargar el archivo de Excel y luego utilizar nav-tabs de Bootstrap para crear pestañas separadas para cada hoja, mostrando los datos en un formato de tabla.

¿Cómo cargo y proceso un archivo de Excel en ASP.NET usando una biblioteca .NET?

En ASP.NET, puedes cargar y procesar un archivo de Excel usando el método WorkBook.Load de IronXL. Este método te permite leer el archivo de Excel, iterar a través de sus hojas de trabajo y extraer los datos para mostrarlos o para una manipulación más profunda.

¿Cuáles son las ventajas de usar IronXL para operaciones de Excel en .NET?

IronXL ofrece varias ventajas para operaciones de Excel en .NET, incluyendo soporte para diversos formatos de archivos de Excel, la capacidad de manipular características complejas de Excel como imágenes y formato condicional, y el beneficio de no requerir la instalación de Microsoft Excel en el servidor.

¿Cómo puedo solucionar problemas comunes al crear un visor de Excel en ASP.NET?

Problemas comunes al crear un visor de Excel en ASP.NET se pueden solucionar asegurando que la biblioteca IronXL esté correctamente instalada a través de NuGet, verificando que todos los modelos y controladores necesarios estén implementados correctamente, y comprobando que los archivos de Excel estén en un formato compatible.

¿Es posible editar archivos de Excel directamente desde una página web ASP.NET?

Sí, es posible editar archivos de Excel directamente desde una página web ASP.NET usando IronXL. La biblioteca te permite cargar archivos de Excel en tu aplicación web, modificar datos y guardar los cambios de vuelta al archivo sin problemas.

¿IronXL admite tanto la lectura como la escritura de archivos de Excel?

Sí, IronXL admite tanto la lectura como la escritura de archivos de Excel. Puedes usarlo para leer datos de documentos de Excel existentes y escribir nuevos datos o cambios en archivos de Excel en múltiples formatos, incluyendo XLS, XLSX, y CSV.

¿Qué modelos se deben crear para gestionar datos de Excel en una aplicación ASP.NET MVC?

En una aplicación ASP.NET MVC, deberías crear modelos como ExcelModel para representar hojas de Excel individuales y ExcelViewModel para gestionar una colección de hojas y manejar la carga de archivos y mensajes.

¿Cómo puedo probar las características de IronXL antes de comprarlo?

Puedes probar las características de IronXL descargando la versión de prueba gratuita disponible en su sitio web. Esta prueba te permite explorar las capacidades de la biblioteca en el manejo de archivos de Excel dentro de tus aplicaciones .NET sin ningún costo inicial.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más