How To Export Gridview To Excel in Asp.Net

How To Export Gridview To Excel in Asp.Net

In this tutorial i am explaining How To Export Gridview To Excel In Asp.Net  using C#. In this tutorial i am not exporting Gridview with Paging in Excel.Here i have used XML File a Data Source for Gridview. How to Export Gridview To Excel In Asp.Net using c# helps us many time for reporting purpose. In earlier post we have discussed GridView Auto Refresh.

Design View:-

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
            <RowStyle BackColor="#EFF3FB" />
            <asp:BoundField DataField="ProductId" HeaderText="ProductId" />
            <asp:BoundField DataField="ProductName" HeaderText="ProductName" />
            <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
        Text="Export Data to Excel" />

Code View:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;

public partial class _Default : System.Web.UI.Page 
    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            DataSet ds = new DataSet();
            GridView1.DataSource = ds;
    protected void Button1_Click(object sender, EventArgs e)
        Response.AddHeader("content-disposition", "attachment;filename=GridView_to_Excel.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        StringWriter StringWriter = new System.IO.StringWriter();
        HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);

    public override void VerifyRenderingInServerForm(Control control)


If you observe in above code I added one function that is VerifyRenderingInServerForm this function is used to avoid the error like control must be placed in inside of form tag. If we set VerifyRenderingInServerForm function then compiler will think that controls rendered before exporting and our functionality will work perfectly.