We are going to learn how to Export GridView data to Microsoft Excel at Runtime.

We are using: ASP.NET Framework 4.0, Visual Studio 2010, SQL Server 2008, C#, XHTML 4.01

 Code for ASPX Page (Front-End) Adding GridView and Columns:



















































Adding Export Link



Now Code for ASPX.CS Page (BackEnd):

Namespaces :
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.Configuration;
using System.Drawing;
using System.IO;
using System.Text;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;

BindGridView Function
void GVProsFill()


        string Query = "Select * from Parties,  Prosperity where Parties.PartyID=Prosperity.ProParty";

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConToMyDB"].ConnectionString);

        SqlDataAdapter adp = new SqlDataAdapter(Query, con);

        DataSet ds = new DataSet();


        gvPros.DataSource = ds.Tables[0];



Export LinkButton Click Event:
//You have to add an another Event for Export to work properly:

public override void VerifyRenderingInServerForm(Control control) 


         // Can Leave This Blank. 


protected void lnkExport_Click(object sender, EventArgs e)



        Response.Buffer = true;

        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Prosperity.xls"));

        Response.ContentType = "application/ms-excel";

        StringWriter sw = new StringWriter();

        HtmlTextWriter htw = new HtmlTextWriter(sw);

        gvPros.AllowPaging = false;


        gvPros.HeaderRow.Style.Add("background-color", "#FFFFFF");

        for (int i = 0; i < gvPros.HeaderRow.Cells.Count; i++)


            gvPros.HeaderRow.Cells.Style.Add("background-color", "#507CD1");


        int j = 1;

        foreach (GridViewRow gvrow in gvPros.Rows)


            gvrow.BackColor = Color.White;

            if (j <= gvPros.Rows.Count)


        if (j % 2 != 0)


        for (int k = 0; k < gvrow.Cells.Count; k++)


            gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");









I will be waiting to Listen from you....