Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
See more:
Hello,

I am trying to get excel sheet from gridview. Following is my code:

string excelXml = GetExcelXml(dsInput, filename);
response.Clear();
response.AppendHeader("Content-Type", "application/vnd.ms-excel");
response.AppendHeader("Content-disposition", "attachment;
filename=" + filename);
response.Write(excelXml);
response.Flush();
response.End();


I am getting exception as "[System.Threading.ThreadAbortException] = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}"

If i remove response.End() i don't see the exception.

What is purpose of response.End().. Why is it throwing error and should I keep it in my code?
Posted

 
Share this answer
 
Comments
Member 8805858 13-Jun-12 7:12am    
Use try catch

try
{
your code
}

catch(ThreadAbortException)
{}
Here is the alternate solution,

C#
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(GetExcelXml(dsInput, filename));
response.Clear();
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
response.Write(sb.ToString());
Response.End();


Hope this may help you...
 
Share this answer
 
Comments
tejashri.gandhi 16-Jan-12 4:37am    
Thanks Mukund,
I will try this
 
Share this answer
 
Comments
Nagamuneendra reddy 23-Jan-12 7:14am    
Even we changed System.Web.HttpContext.Current.Response instead of Response,still it is showing same exception.If it could possible please look into my code what i posted with my question.It is purely related to report exporting into a PDF.
I know its very old question but may be helpful for others...

The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.

Instead of Response.End(), use HttpContext.Current.ApplicationInstance.CompleteRequest()

string excelXml = GetExcelXml(dsInput, filename);
     response.Clear();
     response.AppendHeader("Content-Type", "application/vnd.ms-excel");
     response.AppendHeader("Content-disposition", "attachment;
     filename=" + filename);
     response.Write(excelXml);
     response.Flush();
     //response.End();
     HttpContext.Current.ApplicationInstance.CompleteRequest();


Source: Microsoft official website[^]
 
Share this answer
 
v2
Replace response.End(); with HttpContext.Current.ApplicationInstance.CompleteRequest();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900