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

 Excel File Generate

Gridview show Database Table Values Same As Download To Excel File Using Asp.Net C#



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);

    protected void Page_Load(object sender, EventArgs e)

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

    public override void VerifyRenderingInServerForm(Control control)
    protected void Button2_Click(object sender, EventArgs e)
        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);



      First - Create new WebForm - Select the Buttons & GridView

                Next - Html Coding for Above Design  Part

Next  -  Go to - Coding Part  - Add Namespaces - Database Connection

Next - Write the Select Query Coding to Gridview & Rendering control Coding &  Excel Export coding

                   Next - Press F5 button to Run the Program.

                   Gridview Details Export to Excel Sheet





Post a Comment