Skip to footer content
USING IRONXL

How to Import Excel to GridView in ASP.NET C#

Importing Excel data into a GridView in ASP.NET C# is straightforward with IronXL. You load a workbook, convert a worksheet to a DataTable, and bind it to your GridView control -- all without OLEDB drivers or complex connection strings.

Try it yourself: Grab a free trial of IronXL to follow along with the code examples below.

How Do You Install IronXL for Excel GridView Integration?

Before writing any code, you need to add IronXL to your ASP.NET project. The quickest path is NuGet, either from the Visual Studio Package Manager Console or the .NET CLI.

Install-Package IronXL
dotnet add package IronXL
Install-Package IronXL
dotnet add package IronXL
SHELL

Once installed, NuGet adds all required references to your project. There are no external drivers to install, no OLEDB providers to register, and no Microsoft Office dependency on the server. The library ships as a single managed assembly and works on Windows, Linux, macOS, and cloud hosting environments including Azure App Service.

After installation, add the following namespaces to any code-behind file that reads or writes Excel data:

using IronXL;
using System.Data;
using System.IO;
using IronXL;
using System.Data;
using System.IO;
Imports IronXL
Imports System.Data
Imports System.IO
$vbLabelText   $csharpLabel

IronXL supports both .xls (Excel 97-2003) and .xlsx (Excel 2007+) formats, so you do not need separate handling for each file type. The same WorkBook.Load call handles either format by inspecting the file signature automatically.

Why Skip OLEDB for GridView Data Binding?

Traditional OLEDB-based Excel imports require the Microsoft Access Database Engine (ACE or JET), which must be installed on the server in the correct bitness (32-bit vs. 64-bit). Deployment across different server environments often fails because the driver is missing or mismatched, and Microsoft no longer ships the 64-bit ACE driver with Windows by default.

IronXL eliminates that dependency entirely. It reads the raw Open XML or BIFF format directly in managed code. You get predictable behavior in development, staging, and production without driver version concerns.

What .NET Platforms Does IronXL Target?

IronXL targets .NET 10, .NET 8, .NET Standard 2.0, and .NET Framework 4.6.2+. This coverage means you can use the same library whether your ASP.NET application runs on classic Web Forms, ASP.NET MVC, or modern ASP.NET Core Razor Pages without any code changes to the Excel-handling layer. You can find the IronXL package on NuGet.org to inspect version history and release notes before installing.

What Is the Fastest Way to Load Excel Data into a GridView?

The fastest method combines WorkBook.Load, sheet.ToDataTable, and GridView.DataBind into about four lines of effective code. No manual column creation and no row iteration are required for basic scenarios.

using IronXL;
using System.Data;

WorkBook workBook = WorkBook.Load("data.xlsx");
WorkSheet sheet = workBook.DefaultWorkSheet;

// true = treat first row as column headers
DataTable dataTable = sheet.ToDataTable(true);

GridView1.DataSource = dataTable;
GridView1.DataBind();
using IronXL;
using System.Data;

WorkBook workBook = WorkBook.Load("data.xlsx");
WorkSheet sheet = workBook.DefaultWorkSheet;

// true = treat first row as column headers
DataTable dataTable = sheet.ToDataTable(true);

GridView1.DataSource = dataTable;
GridView1.DataBind();
Imports IronXL
Imports System.Data

Dim workBook As WorkBook = WorkBook.Load("data.xlsx")
Dim sheet As WorkSheet = workBook.DefaultWorkSheet

' True = treat first row as column headers
Dim dataTable As DataTable = sheet.ToDataTable(True)

GridView1.DataSource = dataTable
GridView1.DataBind()
$vbLabelText   $csharpLabel

The ToDataTable(true) call tells IronXL to promote the first row of the worksheet to column names in the resulting DataTable. When you bind that table to a GridView with AutoGenerateColumns="true", ASP.NET creates one column per Excel header automatically.

How Does ToDataTable Handle Mixed Data Types?

Each cell value in the DataTable is stored as a string by default when you call ToDataTable. If your application needs typed columns -- for example, decimal for price data or DateTime for dates -- you can read cell values individually through the WorkSheet indexer and cast them to the appropriate .NET type before populating a strongly typed DataTable.

For simple display in a GridView, string columns are sufficient because the grid renders all values as text anyway.

How Do You Create an ASP.NET Web Forms Page to Import Excel?

A minimal import page needs three controls: a file-upload input, a submit button, and the GridView. Add the following ASPX markup inside your <form runat="server"> element:

<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload Excel File"
    OnClick="btnUpload_Click" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
    CssClass="table table-bordered" />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload Excel File"
    OnClick="btnUpload_Click" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
    CssClass="table table-bordered" />
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload Excel File" OnClick="btnUpload_Click" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" CssClass="table table-bordered" />
$vbLabelText   $csharpLabel

The CssClass attribute wires the grid into your Bootstrap stylesheet if you are using one, giving you styled rows and borders without extra configuration.

In the code-behind, handle the button click event. The pattern below saves the uploaded file to a temporary server path, loads it with IronXL, and binds the resulting DataTable to the grid:

using IronXL;
using System.Data;
using System.IO;

void btnUpload_Click(object sender, EventArgs e)
{
    if (!FileUpload1.HasFile) return;

    string uploadDir = Server.MapPath("~/Uploads/");
    Directory.CreateDirectory(uploadDir); // ensure directory exists

    string filePath = Path.Combine(uploadDir, Path.GetFileName(FileUpload1.FileName));
    FileUpload1.SaveAs(filePath);

    WorkBook workBook = WorkBook.Load(filePath);
    WorkSheet sheet = workBook.DefaultWorkSheet;
    DataTable dt = sheet.ToDataTable(true);

    GridView1.DataSource = dt;
    GridView1.DataBind();

    // Store for later export operations
    Session["CurrentData"] = dt;
}
using IronXL;
using System.Data;
using System.IO;

void btnUpload_Click(object sender, EventArgs e)
{
    if (!FileUpload1.HasFile) return;

    string uploadDir = Server.MapPath("~/Uploads/");
    Directory.CreateDirectory(uploadDir); // ensure directory exists

    string filePath = Path.Combine(uploadDir, Path.GetFileName(FileUpload1.FileName));
    FileUpload1.SaveAs(filePath);

    WorkBook workBook = WorkBook.Load(filePath);
    WorkSheet sheet = workBook.DefaultWorkSheet;
    DataTable dt = sheet.ToDataTable(true);

    GridView1.DataSource = dt;
    GridView1.DataBind();

    // Store for later export operations
    Session["CurrentData"] = dt;
}
Imports IronXL
Imports System.Data
Imports System.IO

Sub btnUpload_Click(sender As Object, e As EventArgs)
    If Not FileUpload1.HasFile Then Return

    Dim uploadDir As String = Server.MapPath("~/Uploads/")
    Directory.CreateDirectory(uploadDir) ' ensure directory exists

    Dim filePath As String = Path.Combine(uploadDir, Path.GetFileName(FileUpload1.FileName))
    FileUpload1.SaveAs(filePath)

    Dim workBook As WorkBook = WorkBook.Load(filePath)
    Dim sheet As WorkSheet = workBook.DefaultWorkSheet
    Dim dt As DataTable = sheet.ToDataTable(True)

    GridView1.DataSource = dt
    GridView1.DataBind()

    ' Store for later export operations
    Session("CurrentData") = dt
End Sub
$vbLabelText   $csharpLabel

This implementation follows top-level statements style for the logic inside the event handler while retaining the required Web Forms event signature. Notice that Directory.CreateDirectory is called defensively -- if the Uploads folder already exists, the call is a no-op.

Import Excel to GridView in ASP.NET C# with IronXL: Uploaded spreadsheet data rendered in a GridView control

After the user selects a .xlsx file and clicks the upload button, the grid populates with the spreadsheet contents. Column names come from the first row of the Excel file, and all subsequent rows become data rows in the grid.

How Should You Validate the Uploaded File?

For production use, you should check the file extension and MIME type before processing. IronXL will throw an exception on unsupported file formats, but it is better to reject bad uploads at the controller level before touching the file system:

string ext = Path.GetExtension(FileUpload1.FileName).ToLowerInvariant();
string[] allowed = { ".xls", ".xlsx" };

if (!allowed.Contains(ext))
{
    lblError.Text = "Only .xls and .xlsx files are accepted.";
    return;
}
string ext = Path.GetExtension(FileUpload1.FileName).ToLowerInvariant();
string[] allowed = { ".xls", ".xlsx" };

if (!allowed.Contains(ext))
{
    lblError.Text = "Only .xls and .xlsx files are accepted.";
    return;
}
Imports System.IO

Dim ext As String = Path.GetExtension(FileUpload1.FileName).ToLowerInvariant()
Dim allowed As String() = {".xls", ".xlsx"}

If Not allowed.Contains(ext) Then
    lblError.Text = "Only .xls and .xlsx files are accepted."
    Return
End If
$vbLabelText   $csharpLabel

You should also enforce a maximum file size through IIS request limits or by checking FileUpload1.FileBytes.Length against a threshold before calling SaveAs.

How Do You Access Specific Worksheets and Cell Ranges?

When an Excel workbook contains multiple sheets, you need to target a specific one by name rather than relying on DefaultWorkSheet. IronXL provides a GetWorkSheet method that accepts the sheet tab name as a string.

using IronXL;
using System.Data;

WorkBook workBook = WorkBook.Load("sales-report.xlsx");

// Access a named sheet
WorkSheet salesSheet = workBook.GetWorkSheet("Q4 Sales");

// Read a specific cell range
var topTen = salesSheet["A1:E11"];

// Convert the entire workbook to a DataSet (one DataTable per sheet)
DataSet allSheets = workBook.ToDataSet();

// Bind the first sheet's DataTable to the grid
GridView1.DataSource = allSheets.Tables[0];
GridView1.DataBind();
using IronXL;
using System.Data;

WorkBook workBook = WorkBook.Load("sales-report.xlsx");

// Access a named sheet
WorkSheet salesSheet = workBook.GetWorkSheet("Q4 Sales");

// Read a specific cell range
var topTen = salesSheet["A1:E11"];

// Convert the entire workbook to a DataSet (one DataTable per sheet)
DataSet allSheets = workBook.ToDataSet();

// Bind the first sheet's DataTable to the grid
GridView1.DataSource = allSheets.Tables[0];
GridView1.DataBind();
Imports IronXL
Imports System.Data

Dim workBook As WorkBook = WorkBook.Load("sales-report.xlsx")

' Access a named sheet
Dim salesSheet As WorkSheet = workBook.GetWorkSheet("Q4 Sales")

' Read a specific cell range
Dim topTen = salesSheet("A1:E11")

' Convert the entire workbook to a DataSet (one DataTable per sheet)
Dim allSheets As DataSet = workBook.ToDataSet()

' Bind the first sheet's DataTable to the grid
GridView1.DataSource = allSheets.Tables(0)
GridView1.DataBind()
$vbLabelText   $csharpLabel

The ToDataSet method is useful when your application needs to display data from multiple sheets or let the user choose which sheet to view. Each DataTable in the returned DataSet corresponds to one Excel worksheet, and the table name matches the sheet tab name.

Import Excel to GridView in ASP.NET C# with IronXL: Named worksheet data bound to a GridView

How Do You Filter Rows Before Binding to GridView?

If you only want a subset of Excel rows -- for example, rows where a "Status" column equals "Active" -- read the DataTable produced by ToDataTable, apply a DataView filter, and bind the filtered view to the grid:

DataTable dt = sheet.ToDataTable(true);
DataView dv = new DataView(dt)
{
    RowFilter = "Status = 'Active'"
};

GridView1.DataSource = dv;
GridView1.DataBind();
DataTable dt = sheet.ToDataTable(true);
DataView dv = new DataView(dt)
{
    RowFilter = "Status = 'Active'"
};

GridView1.DataSource = dv;
GridView1.DataBind();
Dim dt As DataTable = sheet.ToDataTable(True)
Dim dv As New DataView(dt) With {
    .RowFilter = "Status = 'Active'"
}

GridView1.DataSource = dv
GridView1.DataBind()
$vbLabelText   $csharpLabel

DataView.RowFilter accepts standard SQL WHERE clause syntax -- the same expression language documented in the DataColumn.Expression property on Microsoft Learn -- giving you sorting and filtering without loading a database.

How Do You Compare Import Methods for Excel GridView Binding?

Different approaches to Excel-to-GridView binding have distinct trade-offs. The table below summarizes the most common methods so you can choose the right one for your scenario.

Comparison of Excel import methods for ASP.NET GridView binding
Method Driver Required XLS Support XLSX Support Server Dependency Code Complexity
IronXL (ToDataTable) None Yes Yes None Low
OLEDB / JET ACE/JET Engine Yes Partial 32/64-bit driver High
Open XML SDK None No Yes None High
EPPlus None No Yes None (commercial license required for production) Medium

IronXL covers both legacy XLS and modern XLSX formats, requires no server-side driver installation, and provides the lowest code complexity of the options listed. For teams that already use other Iron Software products such as IronPDF or IronOCR, a single Iron Software license covers the full suite.

How Do You Export GridView Data Back to Excel?

Completing the round-trip -- from Excel into a grid and back to Excel -- is equally concise with IronXL. This pattern is useful for "download as Excel" buttons that let users export whatever is currently displayed in the grid.

void btnExport_Click(object sender, EventArgs e)
{
    DataTable dt = Session["CurrentData"] as DataTable;
    if (dt == null) return;

    WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet ws = workBook.CreateWorkSheet("Export");

    // Write header row
    for (int col = 0; col < dt.Columns.Count; col++)
        ws.SetCellValue(0, col, dt.Columns[col].ColumnName);

    // Write data rows
    for (int row = 0; row < dt.Rows.Count; row++)
        for (int col = 0; col < dt.Columns.Count; col++)
            ws.SetCellValue(row + 1, col, dt.Rows[row][col]?.ToString() ?? string.Empty);

    string exportDir = Server.MapPath("~/Exports/");
    Directory.CreateDirectory(exportDir);
    string exportPath = Path.Combine(exportDir, "export.xlsx");
    workBook.SaveAs(exportPath);

    Response.Clear();
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("Content-Disposition", "attachment; filename=export.xlsx");
    Response.TransmitFile(exportPath);
    Response.End();
}
void btnExport_Click(object sender, EventArgs e)
{
    DataTable dt = Session["CurrentData"] as DataTable;
    if (dt == null) return;

    WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet ws = workBook.CreateWorkSheet("Export");

    // Write header row
    for (int col = 0; col < dt.Columns.Count; col++)
        ws.SetCellValue(0, col, dt.Columns[col].ColumnName);

    // Write data rows
    for (int row = 0; row < dt.Rows.Count; row++)
        for (int col = 0; col < dt.Columns.Count; col++)
            ws.SetCellValue(row + 1, col, dt.Rows[row][col]?.ToString() ?? string.Empty);

    string exportDir = Server.MapPath("~/Exports/");
    Directory.CreateDirectory(exportDir);
    string exportPath = Path.Combine(exportDir, "export.xlsx");
    workBook.SaveAs(exportPath);

    Response.Clear();
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("Content-Disposition", "attachment; filename=export.xlsx");
    Response.TransmitFile(exportPath);
    Response.End();
}
Imports System
Imports System.Data
Imports System.IO

Sub btnExport_Click(sender As Object, e As EventArgs)
    Dim dt As DataTable = TryCast(Session("CurrentData"), DataTable)
    If dt Is Nothing Then Return

    Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
    Dim ws As WorkSheet = workBook.CreateWorkSheet("Export")

    ' Write header row
    For col As Integer = 0 To dt.Columns.Count - 1
        ws.SetCellValue(0, col, dt.Columns(col).ColumnName)
    Next

    ' Write data rows
    For row As Integer = 0 To dt.Rows.Count - 1
        For col As Integer = 0 To dt.Columns.Count - 1
            ws.SetCellValue(row + 1, col, If(dt.Rows(row)(col)?.ToString(), String.Empty))
        Next
    Next

    Dim exportDir As String = Server.MapPath("~/Exports/")
    Directory.CreateDirectory(exportDir)
    Dim exportPath As String = Path.Combine(exportDir, "export.xlsx")
    workBook.SaveAs(exportPath)

    Response.Clear()
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    Response.AddHeader("Content-Disposition", "attachment; filename=export.xlsx")
    Response.TransmitFile(exportPath)
    Response.End()
End Sub
$vbLabelText   $csharpLabel

The Response.TransmitFile call streams the saved file to the browser, triggering a download dialog. The Content-Disposition: attachment header ensures browsers download rather than attempt to display the file inline.

Import Excel to GridView in ASP.NET C# with IronXL: DataTable exported back to an Excel file

What Are Common IronXL Formatting Options for Exports?

Beyond raw data, IronXL lets you apply cell formatting before saving. You can set bold headers, column widths, number formats, and background colors:

// Bold the header row
ws["A1:Z1"].Style.Font.Bold = true;

// Apply a currency format to column C (index 2), rows 2 onward
ws[$"C2:C{dt.Rows.Count + 1}"].FormatString = IronXL.Styles.BuiltinFormats.Accounting2;

// Auto-fit column widths (IronXL approximates based on content length)
ws.AutoSizeColumn(0);
ws.AutoSizeColumn(1);
// Bold the header row
ws["A1:Z1"].Style.Font.Bold = true;

// Apply a currency format to column C (index 2), rows 2 onward
ws[$"C2:C{dt.Rows.Count + 1}"].FormatString = IronXL.Styles.BuiltinFormats.Accounting2;

// Auto-fit column widths (IronXL approximates based on content length)
ws.AutoSizeColumn(0);
ws.AutoSizeColumn(1);
' Bold the header row
ws("A1:Z1").Style.Font.Bold = True

' Apply a currency format to column C (index 2), rows 2 onward
ws($"C2:C{dt.Rows.Count + 1}").FormatString = IronXL.Styles.BuiltinFormats.Accounting2

' Auto-fit column widths (IronXL approximates based on content length)
ws.AutoSizeColumn(0)
ws.AutoSizeColumn(1)
$vbLabelText   $csharpLabel

These formatting calls use the IronXL cell styling API, which mirrors the object model of the Excel file format without requiring Interop.

What Are Your Next Steps?

You now have a complete, driver-free pipeline for importing Excel files into an ASP.NET GridView and exporting GridView data back to Excel using IronXL. Here is what to explore next to build on this foundation:

  • Read the IronXL documentation for the full API reference, including formula evaluation, cell range operations, and chart creation.
  • Explore the IronXL code examples library for ready-to-run snippets covering CSV import, password-protected workbooks, conditional formatting, and more.
  • Try the Excel to DataTable tutorial if you want deeper coverage of typed column mapping and null handling.
  • Check the IronXL licensing page to review options from development licenses to OEM redistribution.
  • Review Iron Software's .NET Excel reading guide to understand workbook and worksheet navigation in detail.
  • Compare IronXL with alternatives using the C# Excel library comparison for a feature-by-feature breakdown against OLEDB, EPPlus, and the Open XML SDK.

For .NET Core and ASP.NET Core applications, the same IronXL API works in Razor Pages and MVC controllers. The IronXL ASP.NET Core guide walks through the differences in file upload handling and dependency injection patterns.

If you are integrating IronXL alongside document generation, the IronPDF integration guide shows how to export GridView data to a PDF report in addition to Excel -- useful for applications that need both formats.

Start with the IronXL free trial to test all features in your project before purchasing. No credit card is required for the trial license.

Frequently Asked Questions

What is the benefit of using IronXL for importing Excel to GridView in ASP.NET C#?

Using IronXL simplifies the process of importing Excel data to GridView in ASP.NET C# by eliminating the need for complex OLEDB connection strings and driver installations. It allows developers to load XLS and XLSX files, convert them to DataTables, and display them in GridView controls with straightforward code.

How does IronXL handle different Excel file formats?

IronXL supports various Excel file formats, including XLS and XLSX, making it a versatile tool for importing data into GridView. It ensures compatibility and ease of use across different Excel versions.

Can IronXL convert Excel files to DataTables?

Yes, IronXL can convert Excel files into DataTables, which can then be easily displayed in GridView controls in ASP.NET C#. This feature streamlines the process of data manipulation and visualization.

Is IronXL suitable for large Excel files?

IronXL is designed to handle large Excel files efficiently, making it a reliable choice for projects that require importing substantial amounts of data into GridView in ASP.NET C#.

What are the common issues avoided by using IronXL?

By using IronXL, developers can avoid common issues such as dealing with OLEDB connection strings, server driver compatibility, and complex data import processes, thus reducing debugging time.

Does IronXL require any special server configurations?

No, IronXL does not require special server configurations or additional drivers, which simplifies deployment and reduces maintenance overhead.

How does IronXL improve development productivity?

IronXL improves development productivity by providing a simple and efficient way to import Excel data to GridView in ASP.NET C#, allowing developers to focus on other critical tasks without getting bogged down by data import complexities.

Can IronXL be integrated with existing ASP.NET C# applications?

Yes, IronXL can be easily integrated into existing ASP.NET C# applications, enabling seamless Excel data import to GridView without significant changes to the application architecture.

What programming languages are supported by IronXL?

IronXL is primarily designed for use in C# and ASP.NET environments, providing robust support and integration for these programming languages.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he ...
Read More

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me