IRONSOFTWAREHOME
USING IRONXL

How to Export to Excel from GridView in C# Using IronXL

Curtis Chau
Curtis Chau
Updated: August 1, 2026

Exporting GridView data to a genuine Excel file is one of the most common requirements in ASP.NET web applications. Traditional approaches using HtmlTextWriter and StringWriter create fake Excel files that trigger browser warnings and format errors when users try to open them. This guide shows you how to export GridView data to properly formatted .xlsx files using IronXL -- eliminating the headaches developers face with legacy methods.

Why Does the Traditional GridView Export Approach Cause Problems?

The classic method to export to Excel from GridView in ASP.NET C# involves rendering HTML and setting Response headers with Content-Disposition attachment filename values. This approach requires overriding public override void VerifyRenderingInServerForm to avoid runtime errors. The resulting file is not a true Excel file -- it is HTML masquerading with an .xls extension, causing Excel to display warning messages when users open it.

Specifically, the traditional technique has these drawbacks:

  • Excel shows a "The file format and extension don't match" warning on every open
  • Formatting and data types are lost because the data is stored as raw HTML
  • You must implement VerifyRenderingInServerForm as a workaround, adding technical debt to your project
  • The resulting file lacks proper cell metadata, making it unusable for downstream automation or reporting tools

IronXL solves these issues by creating genuine .xlsx Excel files without requiring Microsoft Office installation on the server. You get a file that any spreadsheet application can open cleanly, with proper data types, styling, and OOXML structure preserved.

How Do You Install IronXL in Your ASP.NET Project?

Before writing any export logic, add IronXL to your project using the NuGet Package Manager. Open the Package Manager Console in Visual Studio and run:

PM > Install-Package IronXL.Excel

Alternatively, search for IronXL.Excel in the NuGet Package Manager UI and install it from there. Once installed, you can reference the IronXL namespace in any code-behind file.

IronXL targets .NET Standard 2.0 and above, so it works with modern ASP.NET Core projects as well as classic ASP.NET Framework applications. No COM interop, no Office installation, and no additional native dependencies are required on your web server.

For more details, see the IronXL installation guide and the IronXL NuGet package page.

How Do You Set Up the ASP.NET GridView for Export?

Create your Default.aspx page with a GridView control and an export button. The markup is standard Web Forms:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="GridViewExportTest.Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
    <title>Export GridView to Excel</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h2>IronXL GridView Export Demo</h2>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
                HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White" CellPadding="5">
            </asp:GridView>
            <br />
            <asp:Button ID="btnExport" runat="server" Text="Export to Excel (.xlsx)"
                OnClick="btnExport_Click" />
        </div>
    </form>
</body>
</html>

This markup creates a simple page with a bound GridView and a button that triggers the export. The AutoGenerateColumns="true" attribute means the grid reads column names directly from the bound DataTable.

Binding Sample Data to the GridView

In your code-behind, bind a DataTable to the grid and store it in Session for later use during the export postback:

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

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

        private void BindGridView()
        {
            DataTable dt = new DataTable("Employees");
            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, "Mike Wilson", "Sales", 70000);
            dt.Rows.Add(4, "Emily Davis", "Engineering", 80000);

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

            // Store DataTable in Session for export postback
            Session["GridData"] = dt;
        }
    }
}

Storing the DataTable in Session avoids re-querying the database or rebuilding data during the postback triggered by the export button. For real applications, replace the hard-coded rows with a database query using Entity Framework or ADO.NET.

Export to Excel from GridView in ASP .NET C#: A Clean C# Solution: Image 1 - UI showing the sample GridView data

How Do You Export GridView Data to Excel Using IronXL?

The clean approach to GridView export converts your DataTable to an IronXL WorkBook and streams the result directly to the browser. Here is the complete export method:

protected void btnExport_Click(object sender, EventArgs e)
{
    ExportGridViewToExcel();
}

private void ExportGridViewToExcel()
{
    DataTable dt = (DataTable)Session["GridData"];

    // Create a workbook and load data from the DataTable
    WorkBook workbook = WorkBook.Create();
    WorkBook.LoadWorkSheetsFromDataSet(new DataSet { Tables = { dt } }, workbook);
    WorkSheet worksheet = workbook.DefaultWorkSheet;

    // Apply header row formatting
    var headerRange = worksheet["A1:D1"];
    headerRange.Style.Font.Bold = true;
    headerRange.Style.Font.Size = 12;
    headerRange.Style.SetBackgroundColor("#3AC0F2");

    // Stream the file to the browser
    string filename = "GridViewExport_" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
    Response.Clear();
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;filename=" + filename);
    workbook.SaveAsStream(Response.OutputStream, IronXL.Enum.FileFormat.Xlsx);
    Response.Flush();
    Response.End();
}

How the Export Works Step by Step

The process breaks down into three logical steps:

  1. Retrieve the DataTable -- Session["GridData"] returns the same DataTable that was bound to the grid. This avoids duplicate database calls.
  2. Build the WorkBook -- WorkBook.LoadWorkSheetsFromDataSet automatically creates one worksheet per DataTable in the DataSet, copying column headers and row values into the appropriate cells.
  3. Stream to the browser -- Setting Content-Type to the OOXML MIME type and writing to Response.OutputStream triggers a browser download with the correct .xlsx extension. No temporary file is written to disk.

This is fundamentally different from the legacy HtmlTextWriter approach. The exported file uses the Open XML format -- the same format that Microsoft Excel uses natively -- so it opens without warnings.

For more information on loading data programmatically, see the IronXL WorkBook documentation and how to export DataTable to Excel in C#.

Export to Excel from GridView in ASP .NET C#: A Clean C# Solution: Image 2 - Exported Excel file

How Do You Save the Excel File to Disk Instead of Streaming It?

If your application needs to archive exports on the server before delivering a download link to the user, save the workbook to a file path rather than streaming it to Response.OutputStream:

private void SaveExcelToDisk(WorkBook workbook, string exportFolder)
{
    // Ensure the exports directory exists
    if (!System.IO.Directory.Exists(exportFolder))
    {
        System.IO.Directory.CreateDirectory(exportFolder);
    }

    string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
    string filename = System.IO.Path.Combine(exportFolder, $"Report_{timestamp}.xlsx");

    workbook.SaveAs(filename);

    // Return the relative path for generating a download link
    string relativePath = "~/Exports/Report_" + timestamp + ".xlsx";
    Response.Write($"<script>alert('File saved to {relativePath}');</script>");
}

Choosing Between Streaming and Disk Save

Comparison of streaming vs. disk-save export strategies
StrategyProsConsBest For
Stream to browserNo disk usage, immediate deliveryCannot archive or re-sendOn-demand user exports
Save to diskFile persists for audit, re-download, or emailRequires cleanup job, disk space managementScheduled reports, audit trails

For most interactive web applications, streaming directly to the browser is the right choice. Save to disk when you need to email the file, store it for compliance, or allow re-downloads from a file management page.

How Do You Apply Advanced Formatting to the Exported Excel Sheet?

IronXL gives you fine-grained control over cell styles, column widths, number formats, and more. The following example shows how to build a professionally styled export:

private void ExportWithFormatting()
{
    DataTable dt = new DataTable("Products");
    dt.Columns.Add("Product", typeof(string));
    dt.Columns.Add("Category", typeof(string));
    dt.Columns.Add("Price", typeof(decimal));
    dt.Columns.Add("InStock", typeof(bool));

    dt.Rows.Add("Widget A", "Hardware", 29.99m, true);
    dt.Rows.Add("Widget B", "Hardware", 49.99m, false);
    dt.Rows.Add("Service Plan", "Support", 199.00m, true);

    WorkBook workbook = WorkBook.Create();
    WorkBook.LoadWorkSheetsFromDataSet(new DataSet { Tables = { dt } }, workbook);
    WorkSheet sheet = workbook.WorkSheets[0];

    // Style the header row
    sheet["A1:D1"].Style.Font.Bold = true;
    sheet["A1:D1"].Style.Font.Size = 13;
    sheet["A1:D1"].Style.SetBackgroundColor("#2196F3");
    sheet["A1:D1"].Style.Font.Color = "#FFFFFF";

    // Apply currency format to the Price column (column C, rows 2 onwards)
    sheet["C2:C4"].Style.NumberFormat.Format = "$#,##0.00";

    // Auto-size all columns for readability
    for (int col = 0; col < 4; col++)
    {
        sheet.AutoSizeColumn(col);
    }

    // Freeze the header row so it stays visible when scrolling
    sheet.FreezePanes(0, 0, 1, 0);

    workbook.SaveAs("FormattedExport.xlsx");
}

Formatting Options Available in IronXL

IronXL exposes a rich set of formatting properties through the IronXL.Styles namespace:

  • Font styling -- bold, italic, underline, font family, and size
  • Cell background colors -- hex color strings accepted directly
  • Number and date formats -- any Excel format string, including currency, percentage, and date patterns
  • Column width -- manual pixel width or AutoSizeColumn for automatic fitting
  • Freeze panes -- lock header rows or columns during scroll
  • Cell borders -- all four borders with configurable style and color
  • Merge cells -- combine cells across rows or columns for report headers

For the full API reference, see IronXL cell styling documentation and IronXL number formatting.

Export to Excel from GridView in ASP .NET C#: A Clean C# Solution: Image 3 - Exported formatted Excel document

How Do You Handle Large Datasets in GridView Exports?

When the GridView is bound to thousands of rows, a few techniques keep the export fast and memory-efficient:

Paging and Server-Side DataTable

Do not export only the visible page of the GridView. Retrieve the full dataset from your data source into a DataTable before calling WorkBook.LoadWorkSheetsFromDataSet. IronXL writes rows in a single pass without loading the entire workbook into memory multiple times, making it suitable for tens of thousands of rows.

Adding Multiple Worksheets

You can include multiple DataTable objects in the DataSet to produce a workbook with separate tabs:

DataSet exportSet = new DataSet();
exportSet.Tables.Add(GetEmployeeData());    // Sheet 1
exportSet.Tables.Add(GetDepartmentData());  // Sheet 2
exportSet.Tables.Add(GetSalaryReport());    // Sheet 3

WorkBook workbook = WorkBook.Create();
WorkBook.LoadWorkSheetsFromDataSet(exportSet, workbook);

Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=MultiSheetReport.xlsx");
workbook.SaveAsStream(Response.OutputStream, IronXL.Enum.FileFormat.Xlsx);
Response.Flush();
Response.End();

Each DataTable.TableName becomes the worksheet tab name in Excel. This pattern works well for management reports that combine related data across multiple views.

Related guides:

What Are the Key Benefits of Using IronXL for GridView Export?

Using IronXL to export GridView data offers clear advantages over the traditional HTML-wrapping approach:

  • Genuine Excel files -- creates valid .xlsx format that opens without browser warnings or error messages
  • No Office installation required -- works on any web server without Microsoft Excel or Office interop
  • No VerifyRenderingInServerForm override -- eliminates the boilerplate workaround that clutters traditional code
  • Full formatting control -- style cells, apply number formats, freeze panes, and create professional worksheets programmatically
  • Multi-sheet support -- export related datasets as separate tabs in a single workbook
  • Cross-platform compatibility -- functions correctly on Windows and Linux servers, including Docker containers and Azure App Service

The library is available on NuGet and supports all modern .NET targets including .NET 10. It also supports reading and writing other formats such as CSV and ODS, which makes it a single dependency for all spreadsheet needs in your application.

For a side-by-side comparison with other Excel libraries, see IronXL vs ClosedXML and the IronXL feature overview.

What Are Your Next Steps?

You now have everything you need to replace the legacy HtmlTextWriter GridView export with a clean, warning-free IronXL implementation. Here is how to move forward:

  • Try the free trial -- start a free 30-day trial of IronXL with no credit card required and test the export code in your own project
  • Explore more IronXL tutorials -- the IronXL blog covers data import, cell formulas, chart generation, and Excel template workflows
  • Read the API reference -- the IronXL API documentation covers every method on WorkBook, WorkSheet, and the styling API
  • Compare licensing options -- view IronXL pricing to find the right license for your team size and deployment scenario
  • Ask a question -- the Iron Software support team and community forums are available if you run into anything unexpected
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

Related Articles

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required