Skip to footer content
USING IRONXL

Export GridView to Excel XLSX C# Using IronXL

Exporting Data from an ASP.NET GridView to an Excel File

Exporting data from an ASP.NET GridView to an Excel file is a common requirement in .NET Framework applications and modern .NET applications alike. In ASP.NET Web Forms, this is often initiated using server controls such as asp:Button to trigger the export functionality. Whether generating reports for management, sharing datasets with stakeholders, or creating downloadable spreadsheets for end users, developers need a reliable way to convert GridView contents into properly formatted .XLSX files that preserve data integrity and structure.

This article explains how to accomplish this export process using IronXL, a powerful .NET library for Excel file creation. Unlike Excel Interop approaches that require MS Excel installation and struggle in web server environments, IronXL works purely with code to generate native Excel documents. The library handles .XLSX, .XLS, and CSV output formats without requiring Microsoft Office on the server. IronXL, Syncfusion XlsIO, and LargeXlsx are also suitable for handling large datasets and provide robust functionality without the need for Microsoft Office.

This guide demonstrates how to export GridView to Excel XLSX C# using IronXL with complete, working code examples. Each example includes full class structures with object/byval sender and EventArgs e parameters, detailed explanations to help developers understand both the implementation and underlying concepts, and practical techniques for your next Visual Studio project. For web applications, remember to set the response MIME type to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet when delivering .XLSX files to ensure the browser triggers a file download.

Introduction to Exporting GridView

Exporting a GridView to an Excel file is a frequent requirement in modern web applications, especially when users need to analyze, share, or archive data outside the application. By converting GridView data into an Excel file, you enable seamless import into Microsoft Excel, making it easy for users to work with the data in a familiar environment. This article explores the most effective methods for exporting a GridView to an Excel file, focusing on practical solutions that work across different .NET web projects.

How Can I Export GridView Data to Excel Sheet Programmatically?

Exporting GridView data to an Excel worksheet programmatically involves extracting the bound data from the control and writing it to an Excel workbook structure. IronXL simplifies this export process by providing an intuitive API that handles the complexity of the Open XML spreadsheet format internally. Developers work with familiar concepts like workbooks, worksheets, rows, and columns rather than dealing with XML schemas directly.

// Quick example: Create an Excel file with IronXL
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Data");
worksheet["A1"].Value = "Hello from IronXL";
workbook.SaveAs("output.xlsx");
// Quick example: Create an Excel file with IronXL
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Data");
worksheet["A1"].Value = "Hello from IronXL";
workbook.SaveAs("output.xlsx");
$vbLabelText   $csharpLabel

Note: In VB.NET, you would typically see object initialization for the workbook and worksheet using the statements Dim workbook and Dim worksheet. These correspond to the C# object creation shown above, where WorkBook workbook and WorkSheet worksheet are used to create and configure the Excel objects.

Output

Export GridView to Excel XLSX C# Using IronXL: Image 1 - Excel Output

How Do I Set Up IronXL in My ASP.NET Project?

Installing IronXL takes just a few seconds using NuGet Package Manager in Visual Studio. Open the Package Manager Console and run the following code:

Install-Package IronXL.Excel
Install-Package IronXL.Excel
SHELL

Export GridView to Excel XLSX C# Using IronXL: Image 2 - Installation

Alternatively, right-click your project in Solution Explorer, select "Manage NuGet Packages," search for "IronXL," and click Install. The package automatically adds all required references and dependencies to your project. IronXL supports .NET Framework applications (4.6.2 and later), as well as .NET Core and .NET 5/6/7/8, giving you flexibility across different project types and web form configurations.

After installation, add the IronXL namespace along with the System namespace to your code-behind file:

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

How Do I Export a GridView to an Excel File?

The following code demonstrates exporting an ASP.NET GridView control to an Excel file when a user clicks an export button. This example uses a full class structure typical of web form applications.

First, the ASPX markup defines a <asp:GridView> and <asp:Button> with runat="server" attributes, which are standard ASP.NET controls:

<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="true">
</asp:GridView>
<asp:Button ID="btnExport" runat="server" Text="Export to Excel" OnClick="btnExport_Click" />
<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="true">
</asp:GridView>
<asp:Button ID="btnExport" runat="server" Text="Export to Excel" OnClick="btnExport_Click" />
XML

The code-behind file contains the data binding method and export logic:

using System;
using System.Data;
using System.Web.UI;
using IronXL;

public partial class GridViewExport : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridView();
        }
    }

    private void BindGridView()
    {
        // Create new DataTable as data source
        DataTable dt = new DataTable();
        dt.Columns.Add("EmployeeID", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Department", typeof(string));
        dt.Columns.Add("Salary", typeof(decimal));
        dt.Rows.Add(1, "John Smith", "Engineering", 75000);
        dt.Rows.Add(2, "Sarah Johnson", "Marketing", 65000);
        dt.Rows.Add(3, "Michael Chen", "Finance", 70000);
        ViewState["EmployeeData"] = dt;
        gvEmployees.DataSource = dt;
        gvEmployees.DataBind();
    }

    protected void btnExport_Click(object sender, EventArgs e)
    {
        // Create new Excel workbook and worksheet
        WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
        WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
        for (int j = 0; j < gvEmployees.HeaderRow.Cells.Count; j++)
        {
            worksheet.SetCellValue(0, j, gvEmployees.HeaderRow.Cells[j].Text);
        }
        // Export GridView data to Excel worksheet
        for (int i = 0; i < gvEmployees.Rows.Count; i++)
        {
            for (int j = 0; j < gvEmployees.Rows[i].Cells.Count; j++)
            {
                string cellValue = gvEmployees.Rows[i].Cells[j].Text;
                worksheet.SetCellValue(i + 1, j, cellValue);
            }
        }
        // Save Excel file to server path
        string filename = Server.MapPath("~/Exports/EmployeeData.xlsx");
        workbook.SaveAs(filename);
    }
}
using System;
using System.Data;
using System.Web.UI;
using IronXL;

public partial class GridViewExport : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridView();
        }
    }

    private void BindGridView()
    {
        // Create new DataTable as data source
        DataTable dt = new DataTable();
        dt.Columns.Add("EmployeeID", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Department", typeof(string));
        dt.Columns.Add("Salary", typeof(decimal));
        dt.Rows.Add(1, "John Smith", "Engineering", 75000);
        dt.Rows.Add(2, "Sarah Johnson", "Marketing", 65000);
        dt.Rows.Add(3, "Michael Chen", "Finance", 70000);
        ViewState["EmployeeData"] = dt;
        gvEmployees.DataSource = dt;
        gvEmployees.DataBind();
    }

    protected void btnExport_Click(object sender, EventArgs e)
    {
        // Create new Excel workbook and worksheet
        WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
        WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
        for (int j = 0; j < gvEmployees.HeaderRow.Cells.Count; j++)
        {
            worksheet.SetCellValue(0, j, gvEmployees.HeaderRow.Cells[j].Text);
        }
        // Export GridView data to Excel worksheet
        for (int i = 0; i < gvEmployees.Rows.Count; i++)
        {
            for (int j = 0; j < gvEmployees.Rows[i].Cells.Count; j++)
            {
                string cellValue = gvEmployees.Rows[i].Cells[j].Text;
                worksheet.SetCellValue(i + 1, j, cellValue);
            }
        }
        // Save Excel file to server path
        string filename = Server.MapPath("~/Exports/EmployeeData.xlsx");
        workbook.SaveAs(filename);
    }
}
$vbLabelText   $csharpLabel

This implementation creates a new WorkBook instance when the export button is clicked. The nested loops iterate through each GridView row using int i as the row index and write cell values to corresponding Excel worksheet positions using the SetCellValue method.

Output

Export GridView to Excel XLSX C# Using IronXL: Image 3 - GridView Output

Export GridView to Excel XLSX C# Using IronXL: Image 4 - GridView to Excel Output

In VB.NET, this export logic typically lives inside a DataTable-driven procedure that begins with Sub and ends with End Sub, reinforcing the familiar datatable end sub structure used in classic ASP.NET Web Forms projects.

How Can I Add Column Headers and Basic Formatting?

The previous example exports data rows but omits column headers. This enhanced version includes headers extracted from the GridView and applies basic formatting for improved readability in the output Excel file.

protected void btnExport_Click(object sender, EventArgs e)
{
    WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
    // Write column headers from GridView to Excel sheet
    int columnCount = gvEmployees.HeaderRow.Cells.Count;
    for (int i = 0; i < columnCount; i++)
    {
        string headerText = gvEmployees.HeaderRow.Cells[i].Text;
        worksheet.SetCellValue(0, i, headerText);
    }
    // Write data rows starting from row 1
    int rowCount = gvEmployees.Rows.Count;
    for (int i = 0; i < rowCount; i++)
    {
        for (int j = 0; j < gvEmployees.Rows[i].Cells.Count; j++)
        {
            string cellValue = gvEmployees.Rows[i].Cells[j].Text;
            worksheet.SetCellValue(i + 1, j, cellValue);
        }
    }
    // Apply column auto-fit formatting for better display
    worksheet.AutoSizeColumn(0);
    worksheet.AutoSizeColumn(1);
    worksheet.AutoSizeColumn(2);
    worksheet.AutoSizeColumn(3);
    string filename = Server.MapPath("~/Exports/EmployeeReport.xlsx");
    workbook.SaveAs(filename);
}
protected void btnExport_Click(object sender, EventArgs e)
{
    WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
    // Write column headers from GridView to Excel sheet
    int columnCount = gvEmployees.HeaderRow.Cells.Count;
    for (int i = 0; i < columnCount; i++)
    {
        string headerText = gvEmployees.HeaderRow.Cells[i].Text;
        worksheet.SetCellValue(0, i, headerText);
    }
    // Write data rows starting from row 1
    int rowCount = gvEmployees.Rows.Count;
    for (int i = 0; i < rowCount; i++)
    {
        for (int j = 0; j < gvEmployees.Rows[i].Cells.Count; j++)
        {
            string cellValue = gvEmployees.Rows[i].Cells[j].Text;
            worksheet.SetCellValue(i + 1, j, cellValue);
        }
    }
    // Apply column auto-fit formatting for better display
    worksheet.AutoSizeColumn(0);
    worksheet.AutoSizeColumn(1);
    worksheet.AutoSizeColumn(2);
    worksheet.AutoSizeColumn(3);
    string filename = Server.MapPath("~/Exports/EmployeeReport.xlsx");
    workbook.SaveAs(filename);
}
$vbLabelText   $csharpLabel

The HeaderRow property provides access to the GridView's column headers, which are written to row 0 of the Excel worksheet. Data rows then populate starting from row 1 (note the i + 1 offset in the SetCellValue call). This offset is essential to prevent overwriting the header row with data.

How Do I Export Data Using the ViewState?

When the GridView control is bound to a DataTable, accessing the DataSource directly provides cleaner code and better performance than iterating through HTML elements in the user interface.

protected void btnExport_Click(object sender, EventArgs e)
{
    // Cast DataSource to DataTable
    DataTable sourceData = ViewState["EmployeeData"] as DataTable;
    if (sourceData == null)
        return; // or show error
    // In VB.NET, this would be declared as: Dim dt As DataTable
    // Create new workbook and worksheet
    WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet worksheet = workbook.CreateWorkSheet("Report");
    // Write headers from DataTable columns
    for (int i = 0; i < sourceData.Columns.Count; i++)
    {
        worksheet.SetCellValue(0, i, sourceData.Columns[i].ColumnName);
    }
    // Write data rows to Excel
    for (int i = 0; i < sourceData.Rows.Count; i++)
    {
        for (int j = 0; j < sourceData.Columns.Count; j++)
        {
            worksheet.SetCellValue(i + 1, j, sourceData.Rows[i][j].ToString());
        }
    }
    string filename = Server.MapPath("~/Exports/DataExport.xlsx");
    workbook.SaveAs(filename);
}
protected void btnExport_Click(object sender, EventArgs e)
{
    // Cast DataSource to DataTable
    DataTable sourceData = ViewState["EmployeeData"] as DataTable;
    if (sourceData == null)
        return; // or show error
    // In VB.NET, this would be declared as: Dim dt As DataTable
    // Create new workbook and worksheet
    WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet worksheet = workbook.CreateWorkSheet("Report");
    // Write headers from DataTable columns
    for (int i = 0; i < sourceData.Columns.Count; i++)
    {
        worksheet.SetCellValue(0, i, sourceData.Columns[i].ColumnName);
    }
    // Write data rows to Excel
    for (int i = 0; i < sourceData.Rows.Count; i++)
    {
        for (int j = 0; j < sourceData.Columns.Count; j++)
        {
            worksheet.SetCellValue(i + 1, j, sourceData.Rows[i][j].ToString());
        }
    }
    string filename = Server.MapPath("~/Exports/DataExport.xlsx");
    workbook.SaveAs(filename);
}
$vbLabelText   $csharpLabel

This approach extracts column names directly from the DataTable’s Columns collection and retrieves cell values from DataRow objects. Working with the underlying data source eliminates dependencies on GridView rendering and provides consistent results regardless of the control’s visual state, paging configuration, or default display settings.

Output

Export GridView to Excel XLSX C# Using IronXL: Image 5 - Export Using ViewState Output

For scenarios involving large datasets or import data operations, IronXL supports efficient worksheet operations that handle thousands of rows without memory issues. The library can also load and read existing Excel files for data processing workflows.

Handling Errors and Output

When exporting a GridView to an Excel file, it’s important to ensure the export process is reliable and user-friendly. Errors can occur for various reasons—such as file permission issues, invalid data, or unexpected exceptions—so robust error handling is essential. By wrapping your export logic in a try-catch block, you can gracefully handle any issues that arise and provide clear feedback to the user.

Additionally, customizing the output of your export process enhances the user experience. You can specify the file name, choose the appropriate file format, and set the content disposition to control how the Excel file is delivered to the user (for example, as a download attachment).

The following code demonstrates how to handle errors and output when exporting a GridView to an Excel file:

try
{
    // Export GridView to Excel file
    GridViewExport.ExcelExport(GridView1, "ExportedData");
    Response.Write("Export successful! Your Excel file is ready.");
}
catch (Exception ex)
{
    // Handle exception and inform the user
    Response.Write("Error exporting data: " + ex.Message);
}
try
{
    // Export GridView to Excel file
    GridViewExport.ExcelExport(GridView1, "ExportedData");
    Response.Write("Export successful! Your Excel file is ready.");
}
catch (Exception ex)
{
    // Handle exception and inform the user
    Response.Write("Error exporting data: " + ex.Message);
}
$vbLabelText   $csharpLabel

In this example, the export process is wrapped in a try-catch block. If the export is successful, a confirmation message is displayed to the user. If an error occurs, the catch block captures the exception and outputs an error message, ensuring the user is informed about the status of their export. You can further customize the output by setting the file name, file type, and content disposition headers to control how the Excel file is presented to the user during download.

Conclusion

Exporting ASP.NET GridView data to Excel files becomes straightforward with IronXL. The library handles workbook creation, cell population, and file generation without requiring MS Excel or Microsoft Office dependencies on the server. This makes IronXL particularly well-suited for web applications where server-side Excel generation must work reliably across different hosting environments.

The examples in this article demonstrate progressively building from basic export to including column headers and formatting. The DataTable approach shown in the final example provides the most robust solution for production .NET applications, ensuring data integrity regardless of GridView configuration. IronXL's comprehensive feature set also supports reading existing Excel files, working with formulas, and managing multiple worksheets for more complex reporting scenarios. The library handles XLSX and XLS formats natively, and can also write CSV output when needed.

Start your free trial to implement GridView to Excel export in your ASP.NET applications today. For production use, explore IronXL licensing options that include perpetual licenses with dedicated support.

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