Export to Excel from GridView in ASP .NET C#: A Clean C# Solution
Exporting GridView data to a genuine Excel file is a common requirement in ASP.NET web applications. Traditional approaches using HtmlTextWriter and StringWriter create fake Excel files that trigger browser warnings and format errors. In this article, we'll demonstrate how to export GridView data to properly formatted Excel 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 isn't a true Excel file—it's HTML masquerading with an .xls extension, causing Excel to display warning messages when users open it.
IronXL solves these issues by creating genuine .xlsx Excel files without requiring Microsoft Office installation on the server.
How Do I Set Up My ASP.NET Project for Grid View Export?
First, install the IronXL library via NuGet Package Manager in your Visual Studio project:
Install-Package IronXL.Excel
Create your Default.aspx page with a GridView control and export data button:
<%@ 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><%@ 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>How Do I Export GridView Data to Excel Using IronXL?
The answer to clean GridView export lies in converting your data to a DataTable, then using IronXL's worksheets functionality. Here's the complete code-behind that handles page load, data binding, and the export function:
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()
{
// Create sample DataTable with database-style data
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));
// Add rows to simulate database records
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
Session["GridData"] = dt;
}
protected void btnExport_Click(object sender, EventArgs e)
{
ExportGridViewToExcel();
}
private void ExportGridViewToExcel()
{
DataTable dt = (DataTable)Session["GridData"];
// Create workbook and load data from 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 file to browser for download
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();
}
}
}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()
{
// Create sample DataTable with database-style data
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));
// Add rows to simulate database records
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
Session["GridData"] = dt;
}
protected void btnExport_Click(object sender, EventArgs e)
{
ExportGridViewToExcel();
}
private void ExportGridViewToExcel()
{
DataTable dt = (DataTable)Session["GridData"];
// Create workbook and load data from 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 file to browser for download
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();
}
}
}Example Output

The code above demonstrates how to export GridView data without the new HtmlTextWriter and new StringWriter approach. IronXL handles the Excel file creation internally, so there's no need to write HTML or worry about the void VerifyRenderingInServerForm override that causes so many errors in traditional implementations.
How Can I Save the Excel File to Disk Instead?
If your application needs to save the Excel file to the server before allowing the user to download it, modify the export method:
private void SaveExcelToDisk(object sender, EventArgs e)
{
DataTable dt = (DataTable)Session["GridData"];
WorkBook workbook = WorkBook.Create();
DataSet dataSet = new DataSet();
dataSet.Tables.Add(dt.Copy());
WorkBook.LoadWorkSheetsFromDataSet(dataSet, workbook);
// Save to disk
string filename = Server.MapPath("~/Exports/") + "Report.xlsx";
workbook.SaveAs(filename);
// Provide download link to user
Response.Write("<script>alert('File saved successfully!');</script>");
}private void SaveExcelToDisk(object sender, EventArgs e)
{
DataTable dt = (DataTable)Session["GridData"];
WorkBook workbook = WorkBook.Create();
DataSet dataSet = new DataSet();
dataSet.Tables.Add(dt.Copy());
WorkBook.LoadWorkSheetsFromDataSet(dataSet, workbook);
// Save to disk
string filename = Server.MapPath("~/Exports/") + "Report.xlsx";
workbook.SaveAs(filename);
// Provide download link to user
Response.Write("<script>alert('File saved successfully!');</script>");
}Output Excel File

How Do I Apply Advanced Formatting to the Excel Sheet?
IronXL provides extensive control over cells, columns, and rows. Here's how to create a professionally styled Excel file with your GridView data:
private void ExportWithFormatting()
{
DataTable dt = new DataTable();
dt.Columns.Add("Product");
dt.Columns.Add("Price");
dt.Rows.Add("Widget A", "$29.99");
dt.Rows.Add("Widget B", "$49.99");
WorkBook workbook = WorkBook.Create();
WorkBook.LoadWorkSheetsFromDataSet(new DataSet { Tables = { dt } }, workbook);
WorkSheet sheet = workbook.WorkSheets[0];
// Format header row with bold font size
sheet["A1:B1"].Style.Font.Bold = true;
sheet["A1:B1"].Style.Font.Size = 14;
// Auto-fit columns for better display
sheet.AutoSizeColumn(0);
sheet.AutoSizeColumn(1);
workbook.SaveAs("FormattedExport.xlsx");
}private void ExportWithFormatting()
{
DataTable dt = new DataTable();
dt.Columns.Add("Product");
dt.Columns.Add("Price");
dt.Rows.Add("Widget A", "$29.99");
dt.Rows.Add("Widget B", "$49.99");
WorkBook workbook = WorkBook.Create();
WorkBook.LoadWorkSheetsFromDataSet(new DataSet { Tables = { dt } }, workbook);
WorkSheet sheet = workbook.WorkSheets[0];
// Format header row with bold font size
sheet["A1:B1"].Style.Font.Bold = true;
sheet["A1:B1"].Style.Font.Size = 14;
// Auto-fit columns for better display
sheet.AutoSizeColumn(0);
sheet.AutoSizeColumn(1);
workbook.SaveAs("FormattedExport.xlsx");
}Formatted Output

What Are the Key Benefits of This Approach?
Using IronXL to export GridView data offers several advantages:
- 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
- Clean code: Eliminates the need for new HtmlTextWriter, Response manipulation, and form control workarounds
- Full formatting control: Style cells, set font size, add comments, and create professional worksheets
- Cross-platform compatibility: Functions correctly on Windows and Linux servers
The IronXL library transforms what was once a frustrating ASP.NET development task into straightforward, maintainable code that produces professional results. *
Ready to streamline your GridView export functionality? Start a free trial of IronXL and experience hassle-free Excel file generation in your ASP.NET projects. For production deployment, explore IronXL licensing options to find the right fit for your team.









