2009/11/04

Export dataGrid to excel

if you need to export dataGrid to excel sheet you can do it as the following.
1- get dataGrid object with data.
2- create object of HtmlTextWriter.
3- try to write the Grid using HtmlTextWriter in you response.

as the following in button_Click event of any other location you want to perform this action.

string attachment = "attachment; filename=RegisteredUsers.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Charset = "UTF-8";
Response.ContentType = "application/vnd.ms-excel";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
GridView grd = new GridView();
grd.DataSource = EntityDataSource1;
grd.DataBind();

grd.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();

No comments: