【问题标题】:tried exporting data grid to excel, execution goes to Application_Error in Global axax尝试将数据网格导出到 excel,执行转到 Global axax 中的 Application_Error
【发布时间】:2016-09-08 11:40:20
【问题描述】:

我在互联网上搜索并找到了许多将 gridview 导出到 excel 的解决方案。我尝试了所有解决方案,但没有一个对我有用。按照建议,我跟踪了 Application_Error 模块。

在调试时我的执行转到

//Global.asax
protected void Application_Error(object sender, EventArgs e)
    {
        Exception exc = Server.GetLastError();
    }

我得到的异常是 :: 抛出了“System.Web.HttpUnhandledException”类型的异常。

我无法弄清楚我做错了什么。任何人都可以建议我,发生了什么。

private void ExportGridToExcel()
        {
            try
            {
                Response.Clear();
                Response.Buffer = true;
                Response.ClearContent();
                Response.ClearHeaders();
                Response.Charset = "";
                string FileName = "PatientCount_" + DateTime.Now + ".xls";
                StringWriter strwritter = new StringWriter();
                HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
                GridView1.GridLines = GridLines.Both;
                GridView1.HeaderStyle.Font.Bold = true;
                GridView1.RenderControl(htmltextwrtter);
                Response.Write(strwritter.ToString());
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.SuppressContent = true;
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            catch (Exception ex) { }
        }

在调试时我没有收到任何异常,但在执行此代码后,执行转到 Global.asax 文件 Application_Error 模块。

请帮帮我!!!

【问题讨论】:

    标签: c# asp.net excel global-asax


    【解决方案1】:

    Server.GetLastError() 是你的朋友——在 Application_Error 方法中使用它来获取最后遇到的异常,看看你能从中学到什么。 Look here 了解有关处理此类应用程序级错误的更多详细信息。

    【讨论】:

    • 感谢您的帮助。我跟踪了代码并编辑了我的问题。请你现在帮我。
    • 我猜你正在使用 ASP.NET MVC?如果你是,你可以返回一个 File 对象而不是修改响应 - 你可能会发现这更容易,如果它仍然失败,你应该得到一个更有意义的异常。看看this SO question 作为起点,它涵盖了一些常见的陷阱并有一些好的解决方案。此外,检查您在 Application_Error 中遇到的异常的 InnerExceptions
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2015-12-07
    相关资源
    最近更新 更多