Read Excel Files in ASP.NET MVC Using C# with IronXL

IronXL enables ASP.NET MVC developers to read Excel files directly in C# without Microsoft Office dependencies, converting Excel data to DataTables for easy display in web views with just a few lines of code.

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

How Do I Create an ASP.NET Project for Excel Reading?

Why Does Visual Studio 2022 Work Best for This?

Using Visual Studio 2022, create a new ASP.NET project. Visual Studio 2022 provides excellent support for .NET 6+ frameworks, improved IntelliSense for IronXL methods, and better performance when working with large Excel files. The IDE's NuGet integration makes installing IronXL particularly straightforward.

What Project Template Should I Choose?

For reading Excel files in ASP.NET, choose the "ASP.NET Core Web App (Model-View-Controller)" template. This template provides a clean MVC structure that separates data processing (Excel reading) from presentation logic. The MVC pattern works perfectly with IronXL's DataTable conversion, allowing you to load spreadsheets in controllers and display them in views seamlessly.

IronXL works with .NET Framework 4.6.2+ and .NET Core 3.1+. For new ASP.NET MVC projects, use .NET 6.0 or higher for optimal performance and security. These versions offer improved memory management when processing large Excel files and better async/await support for converting spreadsheet file types.

How Do I Install the IronXL Library?

What Are the Installation Requirements?

Start using IronXL in your project today with a free trial.

First Step:
green arrow pointer


Which Installation Method Is Fastest?

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

Install-Package IronXL.Excel

How Can I Verify the Installation?

To verify IronXL is properly installed, check your project's dependencies in Solution Explorer. You should see "IronXL" listed under "Dependencies > Packages". Additionally, try adding using IronXL; at the top of your controller file - IntelliSense should recognize the namespace immediately. For troubleshooting installation issues, visit the licensing guide.

How Do I Read an Excel File in My Controller?

What Code Goes in the Controller Action?

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

using IronXL;
using System.Data;

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.
    // The 'true' parameter uses the first row as column headers
    var dataTable = workSheet.ToDataTable(true);

    // Send the DataTable to the view for rendering.
    return View(dataTable);
}
using IronXL;
using System.Data;

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.
    // The 'true' parameter uses the first row as column headers
    var dataTable = workSheet.ToDataTable(true);

    // Send the DataTable to the view for rendering.
    return View(dataTable);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Why Use DataTable Instead of Other Formats?

In the Index action method, 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, select the first Excel sheet as the working sheet and load the data contained in it into a DataTable object. Finally, send the DataTable to the frontend.

DataTable is ideal for ASP.NET MVC because it integrates seamlessly with Razor views and provides built-in support for iterating through rows and columns. Unlike custom objects, DataTable doesn't require model mapping and handles mixed data types automatically. You can also export DataSet and DataTable back to Excel when needed.

What About Error Handling for Missing Files?

Robust error handling ensures your application doesn't crash when Excel files are missing or corrupted. Here's an enhanced version with proper exception handling:

public ActionResult Index()
{
    try
    {
        string filePath = @"C:\Files\Customer Data.xlsx";

        // Check if file exists before attempting to load
        if (!System.IO.File.Exists(filePath))
        {
            ViewBag.Error = "Excel file not found at specified location.";
            return View(new DataTable());
        }

        // Load workbook with error handling
        WorkBook workBook = WorkBook.Load(filePath);

        // Verify worksheet exists
        if (workBook.WorkSheets.Count == 0)
        {
            ViewBag.Error = "No worksheets found in the Excel file.";
            return View(new DataTable());
        }

        WorkSheet workSheet = workBook.WorkSheets.First();
        var dataTable = workSheet.ToDataTable(true);

        return View(dataTable);
    }
    catch (Exception ex)
    {
        // Log the exception (consider using a logging framework)
        ViewBag.Error = $"Error reading Excel file: {ex.Message}";
        return View(new DataTable());
    }
}
public ActionResult Index()
{
    try
    {
        string filePath = @"C:\Files\Customer Data.xlsx";

        // Check if file exists before attempting to load
        if (!System.IO.File.Exists(filePath))
        {
            ViewBag.Error = "Excel file not found at specified location.";
            return View(new DataTable());
        }

        // Load workbook with error handling
        WorkBook workBook = WorkBook.Load(filePath);

        // Verify worksheet exists
        if (workBook.WorkSheets.Count == 0)
        {
            ViewBag.Error = "No worksheets found in the Excel file.";
            return View(new DataTable());
        }

        WorkSheet workSheet = workBook.WorkSheets.First();
        var dataTable = workSheet.ToDataTable(true);

        return View(dataTable);
    }
    catch (Exception ex)
    {
        // Log the exception (consider using a logging framework)
        ViewBag.Error = $"Error reading Excel file: {ex.Message}";
        return View(new DataTable());
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

How Can I Select Different Worksheets?

IronXL provides multiple ways to select and work with specific worksheets. You can access worksheets by index, name, or iterate through all available sheets:

// Method 1: Select by worksheet name
WorkSheet namedSheet = workBook.GetWorkSheet("Sales Data");

// Method 2: Select by index (zero-based)
WorkSheet secondSheet = workBook.WorkSheets[1];

// Method 3: Select the default/active worksheet
WorkSheet defaultSheet = workBook.DefaultWorkSheet;

// Method 4: Iterate through all worksheets
foreach (WorkSheet sheet in workBook.WorkSheets)
{
    string sheetName = sheet.Name;
    // Process each worksheet
}
// Method 1: Select by worksheet name
WorkSheet namedSheet = workBook.GetWorkSheet("Sales Data");

// Method 2: Select by index (zero-based)
WorkSheet secondSheet = workBook.WorkSheets[1];

// Method 3: Select the default/active worksheet
WorkSheet defaultSheet = workBook.DefaultWorkSheet;

// Method 4: Iterate through all worksheets
foreach (WorkSheet sheet in workBook.WorkSheets)
{
    string sheetName = sheet.Name;
    // Process each worksheet
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

How Do I Display Excel Data on a Web Page?

What View Code Is Required?

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

The working Excel file used in this example is shown below:

Excel spreadsheet with customer names, shipping costs, and unit prices - sample data for web display tutorial

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>

@* Check for errors first *@
@if (ViewBag.Error != null)
{
    <div class="alert alert-danger">
        @ViewBag.Error
    </div>
}

@* Display table only if data exists *@
@if (Model != null && Model.Rows.Count > 0)
{
    <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>
}
else
{
    <p>No data to display.</p>
}
@{
    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>

@* Check for errors first *@
@if (ViewBag.Error != null)
{
    <div class="alert alert-danger">
        @ViewBag.Error
    </div>
}

@* Display table only if data exists *@
@if (Model != null && Model.Rows.Count > 0)
{
    <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>
}
else
{
    <p>No data to display.</p>
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Why Use Bootstrap for Table Styling?

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.

Bootstrap provides responsive table designs that automatically adjust to different screen sizes - crucial for modern web applications. The table-dark class creates an attractive dark-themed table that's easy to read. For more advanced Excel formatting like cell borders and alignment or background patterns and colors, you can apply custom CSS classes based on the original Excel styling.

What Does the Final Output Look Like?

Running the project produces the results shown below:

Bootstrap table displaying Excel customer data with names, shipping costs, and unit prices in ASP.NET MVC application

Bootstrap Table

How Can I Add Headers to the Table?

To display column headers from your Excel file, modify the view code to include a table header section. When calling ToDataTable(true), IronXL automatically uses the first row as column names:

@if (Model != null && Model.Rows.Count > 0)
{
    <table class="table table-dark">
        <thead>
            <tr>
                @foreach (DataColumn column in Model.Columns)
                {
                    <th>@column.ColumnName</th>
                }
            </tr>
        </thead>
        <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 (Model != null && Model.Rows.Count > 0)
{
    <table class="table table-dark">
        <thead>
            <tr>
                @foreach (DataColumn column in Model.Columns)
                {
                    <th>@column.ColumnName</th>
                }
            </tr>
        </thead>
        <tbody>
            @foreach (DataRow row in Model.Rows)
            {
                <tr>
                    @for (int i = 0; i < Model.Columns.Count; i++)
                    {
                        <td>@row[i]</td>
                    }
                </tr>
            }
        </tbody>
    </table>
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This enhancement displays proper column headers like "Customer Name", "Shipping Cost", and "Unit Price" from your Excel file. For more complex scenarios involving named ranges or named tables, IronXL provides additional methods to access structured data directly.

Frequently Asked Questions

How do I read Excel files in ASP.NET MVC without Microsoft Office?

IronXL allows you to read Excel files directly in C# without any Microsoft Office dependencies. Simply install IronXL via NuGet, then use WorkBook.Load() to open your Excel file and convert it to a DataTable with just one line of code: var dataTable = IronXL.WorkBook.Load('CustomerData.xlsx').DefaultWorkSheet.ToDataTable(true);

What is the fastest way to convert Excel data to DataTable in ASP.NET?

IronXL provides the ToDataTable() method that instantly converts Excel worksheets to System.Data.DataTable objects. After loading your workbook with IronXL, access any worksheet and call ToDataTable(true) to include headers. This conversion takes just one line of code and works seamlessly with ASP.NET MVC views.

Which .NET version should I use for Excel file processing in web applications?

IronXL supports .NET Framework 4.6.2+ and .NET Core 3.1+. For new ASP.NET MVC projects, .NET 6.0 or higher is recommended as it offers improved memory management when processing large Excel files with IronXL and better async/await support for spreadsheet operations.

What Visual Studio project template works best for Excel reading functionality?

Choose the 'ASP.NET Core Web App (Model-View-Controller)' template when creating your project. This MVC structure perfectly complements IronXL's DataTable conversion feature, allowing you to load and process Excel files in controllers while displaying the data cleanly in views.

How do I install the Excel reading library in my ASP.NET project?

Install IronXL through the NuGet Package Manager Console by running 'Install-Package IronXL.Excel'. After installation, verify it's properly added by checking your project dependencies and adding 'using IronXL;' to your controller - IntelliSense should recognize the namespace immediately.

Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...

Read More
Ready to Get Started?
Nuget Downloads 1,753,501 | Version: 2025.12 just released