Export Gridview data to Excel using asp.net C# with Example - Dotnetspan.com

In our last article we have shared how to maintain scroll position in gridview while RowEditing Event. Gridview is most important and useful control of Asp.net. You can get too many inbuilt functinality then other Data controls. We will discuss difference between Gridview, repeater and Listview. 
In this article we shared how to Export gridview data to excel using asp.net C#. We have shared basic Example code which you can download for your reference. We are rendering GridView Data to HtmlTextWriter and using HtmlTextWriter and StringWriter we are simply writing render output to file with .xls extension.

Export Gridview Data to Excel using asp.net C#


Database Structure
Column NameData Type
IDint(Primary Key)
First Namevarchar(50)
Last Namevarchar(50)
Cityvarchar(30)
EmailIDvarchar(100)

Sql Query
CREATE TABLE Sample(
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [FirstName] [varchar](50) NULL,
 [LastName] [varchar](50) NULL,
 [City] [varchar](30) NULL,
 [EmailID] [varchar](100) NULL)
We have Pre-Inserted data in our table
ExecuteScalar() Example in asp.net

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Export Grid to Excel</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="gvData" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
                <AlternatingRowStyle BackColor="White" />
                <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <RowStyle BackColor="#EFF3FB" />
            </asp:GridView>
        </div>
        <asp:Button ID="btnExporttoExcel" OnClick="btnExporttoExcel_Click" Text="Export Grid to Excel" runat="server" />
    </form>
</body>
</html>

Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridView();
        }
    }
    /// 
    /// Bind GridView
    /// 
    public void BindGridView()
    {
        string ConnectionString = @"Enter your ConnectionString";
        using (SqlConnection con = new SqlConnection(ConnectionString))
        {
            try
            {
                con.Open();
                string Query = "select FirstName, LastName, City, EmailID from Sample";
                SqlCommand cmd = new SqlCommand(Query, con);
                SqlDataReader sdr = cmd.ExecuteReader(); // get data 
                gvData.DataSource = sdr; // give data source to gridview
                gvData.DataBind(); // bind gridview
            }
            catch
            {
                Response.Write("Error Occur While Processing your Request");
            }
            finally
            {
                con.Close();
            }
        }
    }
    /// 
    /// override to Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time
    /// 
    /// 
    public override void VerifyRenderingInServerForm(Control control)
    {
       // declare your control here
    }
    protected void btnExporttoExcel_Click(object sender, EventArgs e)
    {
        ExportGridToExcel();
    }
    private void ExportGridToExcel()
    {
        Response.Clear();
        Response.ClearHeaders();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=" + "Excelsheet_" + DateTime.Now.Ticks.ToString() + ".xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        StringWriter StringWriter = new System.IO.StringWriter();
        HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);

        gvData.RenderControl(HtmlTextWriter);// render gridview control
        Response.Write(StringWriter.ToString());
        Response.End();
    }
}

Demo
how-to-export-gridview-data-to-excel-dotnetspan.com-img1
Excelsheet Output
how-to-export-gridview-data-to-excel-dotnetspan.com-img2


output Download Sample Code