Published June 28, 2023
How to View Excel in ASP.NET
In this comprehensive tutorial where we're going 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. And 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. We'll use this library 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.
- Open Visual Studio.
- Click File > New > Project.
In the new project window, choose ASP.NET Web Application (.NET Framework) template.
Name your project ExcelViewer, select the project location and click Create.
For this article, we will focus on implementing the Excel viewer functionality in our ASP.NET MVC application.
Adding IronXL to Your Project
We will need IronXL to handle Excel file formats (like .xls, .xlsx, and .csv). IronXL allows us to load Excel documents, read, write, and even modify Excel data. It supports formulas, images, formatting, and much more.
- Right-click your project in Solution Explorer, navigate to Manage NuGet Packages.
- In the NuGet Package Manager, search for IronXL.Excel.
Click on Install to add it to your project.
You can also install IronXL using NuGet Package manager console using the following command:
Install-Package IronXL.Excel
Now that we have IronXL installed, let's move onto the next step.
Building Models
ExcelModel
Our first step is to create a model for our Excel data. The ExcelModel
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
In this class, we define 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
This class will be used as our 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 file for data extraction
We then proceed to create our ExcelController
. This is where the magic happens! We load Excel file using IronXL's WorkBook.Load
function, loop through the worksheets, extract the data and add it to our 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
Here, we first initialize a(n) ExcelViewModel
. We 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 our ExcelViewModel
.
We are going to load and display the following Excel file's data:
6. Create the View
In your Views/Excel directory, create a new HTML file Index.cshtml to display Excel data. Here, we'll 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
In this code example, nav nav-tabs
will generate a list of tabs, each representing a sheet from our Excel file. The corresponding tab content will display the data of the respective sheet in a table format. By doing some changes, we can add a browse button 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.
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 30-day 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 $499.