尝试将数据导出到Excel时出错。

我有一个button,从telerik的RadGrid导出到Excel文档的数据。

但是,当我尝试导出时遇到以下错误:

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

这是我的代码:

 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) { } } } 

我已经尝试了以下解决scheme,基于我在网上find的处理相同问题的post,没有一个解决scheme已经工作:

  • 将“Response.End()”更改为“HttpContext.Current.ApplicationInstance.CompleteRequest()”
  • 将“Response.End()”更改为“HttpContext.Current.Response.End()”
  • finally块中移动“Response.End()”。
  • 将“Response.End()”移动到try-catch范围之外。

上述解决scheme都没有解决这个问题。 任何进一步的build议如何解决这个错误是非常感激的。

谢谢。

通过调用Response.End导致exception。 Endlogging的行为是刷新缓冲区并通过放弃当前请求立即中止。 它不用于.NET编程。 这只是为了与旧的ASP代码兼容。

从你的代码中删除Response.End()

你也应该删除catch语句。 应该调查和修正例外情况,而不是被掩盖。 OutOfMemoryException意味着导致泄漏的代码有严重错误。 这可能是因为内存不足或内存碎片太大导致.NET无法分配足够大的块