How to Export GridView Data to Excel in C

Cody Schneider7 min read

Building a feature to export data from a GridView into an Excel file is a common request for any C# web developer. Your users get a clean, offline copy of the data they need, and you provide a feature that makes your application infinitely more useful for reporting and analysis. This guide will walk you through two effective methods to get this done in your ASP.NET application, one for a quick implementation and another for more robust control.

GraphedGraphed

Build AI Agents for Marketing

Build virtual employees that run your go to market. Connect your data sources, deploy autonomous agents, and grow your company.

Watch Graphed demo video

Choose Your Method: Quick & Easy vs. Powerful & Flexible

There are two primary ways to approach exporting a GridView to Excel in C#. Each has its own set of advantages depending on your project's needs.

  • The Content Type Method: This is a server-side trick that renders your GridView's HTML and tells the browser to open it as an Excel file. It's incredibly fast to implement because it requires no external libraries.
  • The Third-Party Library Method: Using a library like ClosedXML or EPPlus gives you the power to create native Excel files (.xlsx). This approach offers complete control over formatting, formulas, multiple sheets, and other advanced features.

We'll cover both methods step-by-step so you can choose the one that's right for you.

Setting the Stage: A Basic ASP.NET Web Form

Before we start exporting, let's assume you have a basic setup. You have an ASP.NET Web Forms project with a page (.aspx) containing:

  1. A GridView control: It's populated with data from a source like a database, a DataTable, or a List<T>.
  2. A Button control: This button will trigger our export logic in the C# code-behind file.

Your simple .aspx page might look something like this:

<pre>```html <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" /> <br /> <asp:Button ID="btnExport" runat="server" Text="Export to Excel" OnClick="btnExport_Click" /> ```</pre>

And your C# code-behind (YourPage.aspx.cs) to populate the GridView on page load might be:

<pre>```csharp using System, using System.Data, using System.Web.UI, public partial class YourPage : Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindDataToGridView(), } } private void BindDataToGridView() { DataTable dt = new DataTable(), dt.Columns.AddRange(new DataColumn[] { new DataColumn("Id", typeof(int)), new DataColumn("Product", typeof(string)), new DataColumn("Quantity", typeof(int)) }), dt.Rows.Add(1, "Laptop", 15), dt.Rows.Add(2, "Monitor", 22), dt.Rows.Add(3, "Keyboard", 40), GridView1.DataSource = dt, GridView1.DataBind(), } } ```</pre>

Free PDF · the crash course

AI Agents for Marketing Crash Course

Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.

Method 1: The Simple Content-Type Approach

This is the fastest path from GridView to an Excel spreadsheet. We're going to take the HTML rendered by the GridView, package it up, and send it to the user's browser with a special content type that Microsoft Excel understands.

Step-by-Step Implementation

The magic happens entirely inside your button's click event handler. Update your btnExport_Click method with the following code:

<pre>```csharp protected void btnExport_Click(object sender, EventArgs e) { // 1. Set the content type and file name Response.Clear(), Response.Buffer = true, Response.AddHeader("content-disposition", "attachment,filename=YourData.xls"), Response.Charset = "", Response.ContentType = "application/vnd.ms-excel", // 2. Use a StringWriter to capture the GridView's HTML using (System.IO.StringWriter sw = new System.IO.StringWriter()) { System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw), // HACK: To avoid a "control must be placed inside a form tag" error // when your GridView is in a master page. GridView1.RenderControl(hw), // 3. Write the captured HTML to the Response output Response.Output.Write(sw.ToString()), Response.Flush(), Response.End(), } } ```</pre>

You may encounter a runtime error: "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server." This is a common ASP.NET sanity check because controls like GridView expect to be inside a <form runat="server"> tag. Since we're rendering it outside the normal page life cycle, we need to add a simple override to our code-behind file:

<pre>```csharp public override void VerifyRenderingInServerForm(Control control) { // Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time. } ```</pre>

Pros and Cons of This Method

  • Pros:
  • Cons:

Method 2: Using ClosedXML for Native Excel Files

When you need more power and want to deliver a professional, native .xlsx file without any security warnings, a third-party library is the way to go. ClosedXML is a popular, free .NET library built on top of OpenXML that makes creating Excel documents remarkably easy.

GraphedGraphed

Build AI Agents for Marketing

Build virtual employees that run your go to market. Connect your data sources, deploy autonomous agents, and grow your company.

Watch Graphed demo video

Step-by-Step Implementation

1. Install the ClosedXML NuGet Package

First, you need to add the library to your project. You can do this through the NuGet Package Manager Console:

Install-Package ClosedXML

2. Prepare Your Data

ClosedXML works beautifully with a DataTable. Since our GridView is already bound to one, we can reuse the logic from our BindDataToGridView method to get the data.

3. Write the Export Logic

Now, let's update the btnExport_Click event handler to use ClosedXML. The code is clean and highly readable:

<pre>```csharp using ClosedXML.Excel, using System.Data, using System.IO, // ... other using statements protected void btnExport_Click(object sender, EventArgs e) { // Create the DataTable just like we did for the GridView DataTable dt = new DataTable("GridView_Data"), dt.Columns.AddRange(new DataColumn[] { new DataColumn("Id"), new DataColumn("Product"), new DataColumn("Quantity") }), dt.Rows.Add(1, "Laptop", 15), dt.Rows.Add(2, "Monitor", 22), dt.Rows.Add(3, "Keyboard", 40), // Use ClosedXML to create the Excel file using (XLWorkbook wb = new XLWorkbook()) { wb.Worksheets.Add(dt, "Products"), // 1. Set the content type and file name Response.Clear(), Response.Buffer = true, Response.Charset = "", Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", Response.AddHeader("content-disposition", "attachment,filename=YourData.xlsx"), // 2. Save the workbook to a memory stream using (MemoryStream MyMemoryStream = new MemoryStream()) { wb.SaveAs(MyMemoryStream), MyMemoryStream.WriteTo(Response.OutputStream), Response.Flush(), Response.End(), } } } ```</pre>

With just a few lines of code, you now have a robust export feature that produces a real .xlsx file. You can take this even further by adding formatting, like styling headers or autofitting columns:

<pre>```csharp // Example: Add styling before saving the workbook var worksheet = wb.Worksheet(1), var headerRow = worksheet.Row(1), headerRow.Style.Font.Bold = true, headerRow.Style.Fill.BackgroundColor = XLColor.LightGray, worksheet.Columns().AdjustToContents(), // Autofit columns ```</pre>

Free PDF · the crash course

AI Agents for Marketing Crash Course

Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.

Pros and Cons of This Method

  • Pros:
  • Cons:

Handling Common Problems

As you implement your export feature, you might run into a few common hurdles. Here’s how to solve them.

Exporting All Data When GridView is Paged

If your GridView uses paging (AllowPaging="True"), the content type method will only export the data on the current page. To export all data, you need to temporarily disable paging before rendering the control.

<pre>```csharp // In the button-click event, before rendering GridView1.AllowPaging = false, BindDataToGridView(), // Re-bind the GridView with all data // ... render the control ... // After rendering, restore your settings if needed GridView1.AllowPaging = true, BindDataToGridView(), ```</pre>

Note that this is not an issue with the ClosedXML method, as we are creating the DataTable directly from our data source, independent of the GridView's visible state.

Styling Mismatches in Excel

The content type method will bring your website's CSS styles into the Excel file, which might not look great. You can render a "clean" version by temporarily clearing the styles from your GridView object before exporting.

Final Thoughts

Exporting a GridView to Excel is a fundamental skill for C# developers building data-driven web applications. The Content-Type method provides a quick fix for simple needs, while a library like ClosedXML offers a professional, powerful solution for creating true Excel files with full customization.

Building custom reporting features like this is often a necessary part of the job, but can also consume a lot of development time. For teams who want to move faster, we created Graphed to handle this work for you. By connecting your data sources directly to our platform, you can use plain English to create real-time dashboards and reports instantly, enabling your entire team to get answers from your data without ever having to write a line of C# or wait for a custom "Export to Excel" button.

Related Articles