private void btnExportToExcel_Click(object sender,
System.EventArgs e)
{
ExportToExcel("Report.xls",DataGrid1);
}
private void ExportToExcel(string strFileName,DataGrid dg)
{ Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition",
"attachment;filename=" + strFileName);
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter sw = new StringWriter();
System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
6 comments:
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.
Hey, Very useful piece of code. Works great. I have been looking around the net for a simple solution like this. Great Work!
Hi,
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..
Sahil
@Sahil
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.
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. :)
Post a Comment