Monday, April 14, 2008

How to Export Gridview data to Excel

The following line of codes will help you export data in Gridview to Excel without using Excel COM or third party components:

private void ExportGridtoExcel()
{

Response.Clear();
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=OverviewReport.xls");

System.IO.StringWriter objStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter objHTMLTextWriter = new HtmlTextWriter
(objStringWriter);

GridView objGridView = new GridView();
// set the page size to a number that will show all data of the gridview in one page since this
// functionality is dependend on how many data are visible on the first page on the gridview
objGridView.PageSize = 1000;
objGridView.AllowPaging = false;
objGridView.DataSource = dt;
objGridView.DataBind();
objGridView.RenderControl(objHTMLTextWriter);

Response.Write(objStringWriter.ToString());
Response.End();

}

1 comment:

Anonymous said...

We like your blogging style and your themes,
we're selecting some well made blogs to sponsor.
If you want us to link your blog in our site,
subscribe to our site and

1.send us your site/blog address;
2.send us a representative image of your site/blog (if you have got one);
3.send us a brief description of your site.

we would be honored to sponsor you.

Alternatively (or in addition) we purpose you a link exchange to increase your web popularity:
put us in your blogroll and we will put you in our blogroll!!
all for free!

"we give voice to you"

ilinkyoursite staff

"I link your site"