Wednesday, 8 October 2014

How to Export GridView Data to Excel Using Asp.Net C#

 EXCEL FILE GENERATE


        DEMO

C# Coding


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


public partial class Excel : System.Web.UI.Page
{

    SqlConnection con;
    SqlCommand cmd;
    SqlDataAdapter adp;
    SqlDataReader rd;
    DataSet ds;
    string query;

    public void dbcon()
    {
        string connn = (System.Configuration.ConfigurationManager.ConnectionStrings["dbcon"].ToString());
        con = new SqlConnection(connn);
        con.Open();

    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        dbcon();
        query = "select * from register";
        cmd = new SqlCommand(query, con);
        adp = new SqlDataAdapter(cmd);
        ds = new DataSet();
        adp.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();


    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.AddHeader("content-disposition""attachment; filename=CustomerDetails.xls");
        Response.ContentType = "application/excel";
        System.IO.StringWriter sw = new System.IO.StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();

    }

}





             






                


                                                  
                                                                               




                                   



0 comments:

Post a Comment