繁体   English   中英

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

[英]Error when attempting to Export data to Excel.

我有一个按钮,可将数据从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)
        {
        }
    }
}

我已根据网上发现的处理同一问题的帖子尝试过以下解决方案,但这些解决方案均无效:

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

以上解决方案均不能解决问题。 非常感谢您提供有关如何解决此错误的任何其他建议。

谢谢。

您正在通过调用Response.End引发异常。 End记录的行为是刷新缓冲区并通过中止当前请求立即中止当前请求。 .NET编程中未使用它。 它的存在仅是为了与旧的ASP代码兼容。

只需从代码中删除Response.End()

您还应该删除catch语句。 应该对异常进行调查并加以解决,而不应加以掩盖。 OutOfMemoryException表示导致泄漏的代码存在严重问题。 可能是由于内存不足或内存碎片过多导致.NET无法分配足够大的块引起的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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