简体   繁体   中英

Error when attempting to Export data to Excel.

I have a button that exports data from telerik's RadGrid into an Excel document.

However, I am encountering the following error when I attempt to export:

[System.Threading.ThreadAbortException]: 
{Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}

Here's my code:

private void GenerateFile(object structure, string fileName)
{
    Workbook workbook = structure as Workbook;

    var formatProvider = new XlsxFormatProvider();

    try
    {
        using (MemoryTributary ms = new MemoryTributary())
        {
            Response.ClearHeaders();
            Response.ClearContent();
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment; filename=" + fileName);

            formatProvider.Export(workbook, ms);
            ms.Position = 0;
            ms.WriteTo(Response.OutputStream);

            Response.End();
            }
        }
        catch (System.OutOfMemoryException ex)
        {
        }
    }
}

I have tried the following solutions based on posts I have found online that dealt with the same issue, none of the solutions have worked:

  • Change "Response.End()" to "HttpContext.Current.ApplicationInstance.CompleteRequest()"
  • Change "Response.End()" to "HttpContext.Current.Response.End()"
  • Move "Response.End()" inside a finally block.
  • Move "Response.End()" outside of the try-catch scope.

None of the above solutions have solved the issue. Any further advice on how to resolve this error is greatly appreciate it.

Thanks.

You are causing the exception by calling Response.End . End 's documented behavior is to flush buffers and abort the current request immediately by aborting it. It's not used in .NET programming. It's there only for compatibility with old ASP code.

Just remove Response.End() from your code

You should also remove the catch statement. Exceptions should be investigated and fixed, not covered up. An OutOfMemoryException means that there is something seriously wrong with the code that's causing leaks. It can be caused either because you run out of memory or because memory is so fragmented that .NET is unable to allocate a large enough block

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM