Saturday, October 14, 2006

Export Datagrid Data To Excel

private void btnExportToExcel_Click(object sender,
System.EventArgs e)

private void ExportToExcel(string strFileName,DataGrid dg)
{ Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/";
"attachment;filename=" + strFileName);
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter sw = new StringWriter();
System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);


Marcos said...

hi, hey, i use your code and it was very handy, but when i try to implement it on an imageButton, like an element inside the gridview, it doesn`t appears any message.

The exception thrown is
{Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}

Does you or anybody knows how to solve this item?

My sincerily regards.

M3mph15 said...

Hey, Very useful piece of code. Works great. I have been looking around the net for a simple solution like this. Great Work!

sahil said...

i m sahil i m using your code but i m geting only one error can you tell me.about this error is:-

'DataGrid' is an ambiguous reference between 'System.Web.UI.WebControls.DataGrid' And 'System.Windows.Forms.DataGrid'

Can you tell me please..


DotNetGuts said...


Change definition to something like
private void ExportToExcel(string strFileName,Gridview dg)

This code was developed in .Net 1.1, where in we used Datagrid, but for .Net 2.0 or .Net 3.5 you would be normally using GridView so change the reference accordingly.

Rohan said...

I use this code with my gridview.. I have two problems

1) I have a button making the gridview visible.. The button to export then gives this error:

Control 'SortTable' of type 'GridView' must be placed inside a form tag with runat=server.

2) If I keep the gridview hidden, the export button works, but the resulting xls has NO data..

Please help me.. Thanks :)


Thanks It saved my time. :)

Most Recent Post

Community Updates

Subscribe Blog via Email

Enter your email address:

Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape