Export Grid to Excel


Posted Date:     Total Responses: 0    Posted By: Mrs. Meetu Choudhary Nanda   Member Level: Gold   Points/Cash: 155   



Export Grid to Excel


In this article we are going to read and understand how in a web application we can export a grid data in the excel file.



Let's start with creating an application in VS2008 (You can even go for VS2005 or VS2010)



Following the steps to we are going to follow.




  1. Create a new project in VS2008 as name it as "ExporttoExcel" in the C# category.

  2. Place a gridview on the default.aspx page and rename it to grdtoexport.

  3. And place a button which will export the grid to excel.

  4. Now lets create a datatable which will bind the grid.



The Code will look like:


protected void Page_Load(object sender, EventArgs e)


{


//creating a table for the grid use namespace System.Data;


DataTable dt = new DataTable ();


//adding columns to the datatale


try


{


dt.Columns.Add("Srno");


dt.Columns.Add("Name");


}


catch { }


//adding values to the datatable


for (int i = 1; i <= 10; i++)


{


DataRow dr = dt.NewRow();


dr[0] = i;


dr[1] = "Meetu Choudhary " + i.ToString();


dt.Rows.Add(dr);


}


//binding databale to the grid


grdtoexport.DataSource = dt;


grdtoexport.DataBind();



}



Writing a ExportToExcel class



using System;


using System.Collections.Generic;


using System.Linq;


using System.Web;


using System.Data;


using System.Configuration;


using System.Web.Security;


using System.Web.UI;


using System.Web.UI.WebControls;


using System.Web.UI.WebControls.WebParts;


using System.Web.UI.HtmlControls;


using System.Text;


using System.IO;




namespace ExportToExcel


{



/// <summary>


/// Summary description for ExportToExcel


/// </summary>


public class ExportToExcel


{


public ExportToExcel()


{


//


// TODO: Add constructor logic here


//


}


public void ExportGridView(GridView GridView1, String strFileName)


{


PrepareGridViewForExport(GridView1);


//string attachment = "attachment; filename=Contacts.xls";


HttpContext.Current.Response.ClearContent();


HttpContext.Current.Response.Buffer = true;


HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + strFileName);


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


HttpContext.Current.Response.Charset = "";


//System.Web.UI.Page.EnableViewState = false;


StringWriter sw = new StringWriter();


HtmlTextWriter htw = new HtmlTextWriter(sw);


GridView1.RenderControl(htw);


HttpContext.Current.Response.Write(sw.ToString());


HttpContext.Current.Response.End();


}



private void PrepareGridViewForExport(Control gv)


{


LinkButton lb = new LinkButton();


Literal l = new Literal();



string name = String.Empty;


for (int i = 0; i < gv.Controls.Count; i++)


{


if (gv.Controls[i].GetType() == typeof(LinkButton))


{


l.Text = (gv.Controls[i] as LinkButton).Text;


gv.Controls.Remove(gv.Controls[i]);


gv.Controls.AddAt(i, l);


}


else if (gv.Controls[i].GetType() == typeof(DropDownList))


{


l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;


gv.Controls.Remove(gv.Controls[i]);


gv.Controls.AddAt(i, l);


}



else if (gv.Controls[i].GetType() == typeof(CheckBox))


{


l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";


gv.Controls.Remove(gv.Controls[i]);


gv.Controls.AddAt(i, l);


}



if (gv.Controls[i].HasControls())


{


PrepareGridViewForExport(gv.Controls[i]);


}


}


}



/*Use this commented function in all the pages where the above export function is used


//public override void VerifyRenderingInServerForm(Control control)


//{


//}*/



Calling the Function to export on button click



protected void btnexport_Click(object sender, EventArgs e)


{


ExportToExcel ex = new ExportToExcel();


ex.ExportGridView(grdtoexport, "Client.xls");


}







You can download the code from here



Regards, Meetu Choudhary
Microsoft MVP-ASP/ASP.NET

MsDnM || My Forums || My Blog


Project Feedbacks

Author: Member Level: BronzeRevenue Score: 5 out of 55 out of 55 out of 55 out of 55 out of 5
Hi Meetu,
I am very new to this site .the main aim to come this site to brush up my prpgraming skills.Actully i have done MCA in 2005 and i enter in GIS Field currently i am GIS professional and am working in Doha(Qatar)at good position.
But i am very much intrested in web programming so can you please suggest me some simple project with proper guide line.or if possible please write a simple priject for me.My C# and asp.net basic are clear .
and can develope single .net page but connecting a data base is difficult for me so plz..plz.. write me small project with Access database
So please help me in this connection awating your kind responce my email: imohdarif@gmail.com
thanks a lot


Author: Member Level: BronzeRevenue Score: 3 out of 53 out of 53 out of 5
The Export to Excel can be done by
1. Setting the provider name as the Excel 2007
2. Inherits the class gridview and
read the data from it and using the streamwriter write the data to the Excel file.


Author: Member Level: BronzeRevenue Score: 2 out of 52 out of 5
This will not working can you please help to execute whole documented code please send your responese to veerendra.529@gmail.com.


Author: Member Level: BronzeRevenue Score: 2 out of 52 out of 5
hi..i am not able to download this project through the above link.so please could you send its source code at my email-id vikasthakur86@gmail.com. plz.it's urgient..thanks


Author: Member Level: BronzeRevenue Score: 1 out of 5
its nice
can u tell how to do this in vb instead if c#


Author: Member Level: GoldRevenue Score: 1 out of 5
good one...
It can be include in reusable component


Author: Member Level: GoldRevenue Score: 1 out of 5
good one...
It can be include in reusable component


Author: Member Level: GoldRevenue Score: 1 out of 5
Good one


Author: Member Level: SilverRevenue Score: 2 out of 52 out of 5
how to export Image in asp.net page to Excel sheet

please send me reply as soon as possible ..
i am eagerly waiting for answers


Author: Member Level: SilverRevenue Score: 2 out of 52 out of 5
hi experts

can you help me .. i want to export images from my page to Excel sheet

plz help ..

and give me Source code if it is possible...

thnaks


Author: Member Level: GoldRevenue Score: 2 out of 52 out of 5
Hi,
Its really nice. I would like learn such type of things.

It will be greatful for me to send the files.

Thanks
Siva Sreenath


Author: Member Level: GoldRevenue Score: 1 out of 5
its good yar


Author: Member Level: GoldRevenue Score: 2 out of 52 out of 5
I don't think this is a project.

It should have been included in code snippets section...

Nothing yaar.




Post Feedback
You must Sign In to post a feedback.
Next Project: The Quiz
Previous Project: Exposing a Weather Web Service Report

Return to Project Index

Post New Project


Related Projects


Top Contributors
Today
    Last 7 Daysmore...

    Awards & Gifts

    Online Members

    More...
     
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India