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

5 comments:

Anonymous said...

this.ClearControls(DataGridView);
Please supply code for ClearControls(..)

DataGridView.RenderControl(oHtmlTextWriter);
I cannot reference datagridview directly because it exists in the datalist control.

Thanx

Moustafa El-Zoughby said...

You can fnd the datagrid by using DataList.FindControl(); to get a datagrid object.

try without clear controls function and let me know ?

jinalshah said...

it will give you error like this while working with master page
'ctl00_CntFormContents_DataList1_ctl01_gvTopFiveMasterIntroducer' of type 'GridView' must be placed inside a form tag with runat=server

Moustafa El-Zoughby said...

do you have MS excel installed in your client machine ? which version ?

Anonymous said...

I encountered that error and found that it is cured by overriding the method
public override void VerifyRenderingInServerForm(Control control)
{
}

We are using a custome Page class, so this override could be placed there. If you're not, then do some searching to find an alternative, but this is probably your root problem.