C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » C# Syntax »

Export Grid to Excel


Posted Date: 06 Aug 2009    Resource Type: Code Snippets    Category: C# Syntax
Author: Miss Meetu ChoudharyMember Level: Diamond    
Rating: 1 out of 5Points: 30




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

For more details, visit http://aspnetbymeetu.blogspot.com/2009/08/export-to-excel.html


Related Resources:
Read articles related to Export to Excel

Responses

Author: Filip    11 Aug 2009Member Level: Silver   Points : 2
Hi,

there is much easier way to export grid to Excel. Try using GemBox Excel component for .NET. It is very easy to use and works very fast. Here is an example how to export grid to Excel with this component.


Author: soniumesh    11 Aug 2009Member Level: Gold   Points : 1
Hi meetu

Your code is good but we can do grid to excel much easier way.

umesh


Author: Miss Meetu Choudhary    12 Aug 2009Member Level: Diamond   Points : 1
Other Wyas are upto you I liked This way... So shared... and by the way there are so many ways to do a single task...


Author: Ramesh N D    20 Aug 2009Member Level: Gold   Points : 0
this is good for web application...what about in Windows Applications....


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Meetuchoudhary  .  Meetu  .  Gridview  .  Export  .  Excel  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Convert binary stream to byte array
Previous Resource: Dataset Into Combobox(C#.NET)
Return to Discussion Resource Index
Post New Resource
Category: C# Syntax


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use