Thursday, March 29, 2007

Export Data List to Excel

Hi Folks,

This post is very tricky because it shows a trick about exporting datalist data to excel.

if you have a dtagrid and you want to export its data to excel,by few lines of code you can export its data to an excel file....here is the code :

/******************* BEGIN CODE ***********************************************/
Response.Clear();
Response.Buffer= true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.ClearControls(DataGridView);
DataGridView.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.Flush();
Response.End();

/*****************************************************************************/

the important thing here,is to export a datalist which contains a composite controls like a datagrid inside a datalist this code will not work,
simply to solve the problem,comment this line of code in export function :

//this.ClearControls(DataGridView);

then simply all child controls in the datalist will be export to Excel.........


Happy .Netting :)

Regards,
Moustafa arafa
Post a Comment