USING IRONXL

How to View Excel in ASP.NET

Updated June 27, 2023
Share:

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. 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 Package Manager Console using 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; }
        public List<string []> Data { get; set; }
    }
}
namespace Excel_File_Viewer_IronXL.Models
{
    public class ExcelModel
    {
        public string SheetName { get; set; }
        public List<string []> Data { get; set; }
    }
}
Namespace Excel_File_Viewer_IronXL.Models
	Public Class ExcelModel
		Public Property SheetName() As String
		Public Property Data() As List(Of String ())
	End Class
End Namespace
VB   C#

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; }
        public string Message { get; set; }
        public List<ExcelModel> ExcelData { get; set; }
    }
}
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;

namespace Excel_File_Viewer_IronXL.Models
{
    public class ExcelViewModel
    {
        public IFormFile File { get; set; }
        public string Message { get; set; }
        public List<ExcelModel> ExcelData { get; set; }
    }
}
Imports Microsoft.AspNetCore.Http
Imports System.Collections.Generic

Namespace Excel_File_Viewer_IronXL.Models
	Public Class ExcelViewModel
		Public Property File() As IFormFile
		Public Property Message() As String
		Public Property ExcelData() As List(Of ExcelModel)
	End Class
End Namespace
VB   C#

This class will be used as the view model. It has a(n) 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
        string filePath = Server.MapPath("~/App_Data/Test.xlsx"); 

    // Replace 'Test.xlsx' with your file name

        List<ExcelModel> data = new List<ExcelModel>();

        try
        {
            // Load workbook directly from a file path
            var workbook = WorkBook.Load(filePath);
            foreach (var worksheet in workbook.WorkSheets)
            {
                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
        string filePath = Server.MapPath("~/App_Data/Test.xlsx"); 

    // Replace 'Test.xlsx' with your file name

        List<ExcelModel> data = new List<ExcelModel>();

        try
        {
            // Load workbook directly from a file path
            var workbook = WorkBook.Load(filePath);
            foreach (var worksheet in workbook.WorkSheets)
            {
                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
		Dim filePath As String = Server.MapPath("~/App_Data/Test.xlsx")

	' Replace 'Test.xlsx' with your file name

		Dim data As New List(Of ExcelModel)()

		Try
			' Load workbook directly from a file path
			Dim workbook = WorkBook.Load(filePath)
			For Each worksheet In workbook.WorkSheets
				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
VB   C#

Here, initialize a(n) ExcelViewModel and then load the WorkBook using IronXL, loop through each WorkSheet, and for each WorkSheet, we create a(n) 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
VB   C#

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 $599.

< PREVIOUS
How to Convert XLS to XLSX File in C#
NEXT >
How To Write Data in CSV File in C#

Ready to get started? Version: 2024.7 just released

Free NuGet Download Total downloads: 897,936 View Licenses >
123