Export Gridview to Excel - Asp.Net


Export Gridview to Excel - Asp.Net

C# - How to export data to excel from gridview and DataTable

In this article I will explain how to export from a GridView data to Excel file. In the below example we will use RenderControl method outputs server control content (to a provided HtmlTextWriter object and stores tracing information) about the control if tracing is enabled.

This method will confirms that an HtmlForm control is rendered for the specified Asp.Net server control at run time.

c# excel,gridview export,excel spreadsheet,export data from excel,excel documents,aspnet,simple example

Default.cs Code:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

public partial class _Default : System.Web.UI.Page
    DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
        dt.Columns.Add("EmpId", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Address", typeof(string));
        dt.Columns.Add("Date", typeof(DateTime));

        // Here we add five DataRows.
        dt.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
        dt.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
        dt.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
        dt.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
        dt.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);

        GridView1.DataSource = dt;
    protected void btnexport_Click(object sender, EventArgs e)
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=gridviewdata.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sWriter = new StringWriter();
            HtmlTextWriter hWriter = new HtmlTextWriter(sWriter);
        catch (Exception ex)
            Label1.Text = ex.ToString();

    public override void VerifyRenderingInServerForm(Control control)

 To download the source code click here

Export Gridview to Excel - Asp.Net Reviewed by Ravi Kumar on 2:58 PM Rating: 5


All Rights Reserved by Etechpulse © 2012 - 2017

Contact Form


Email *

Message *

Powered by Blogger.