Ep

Ep

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;
        GridView1.DataBind();
    }
    protected void btnexport_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Clear();
            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);
            GridView1.RenderControl(hWriter);
            Response.Output.Write(sWriter.ToString());
            Response.Flush();
            Response.End();
        }
        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:00 PM Rating: 5

2 comments:

All Rights Reserved by Etechpulse © 2012 - 2017
Powered By Blogger

Contact Form

Name

Email *

Message *

Powered by Blogger.