尝试将数据网格导出到excel,执行转到Global axax中的Application_Error

时间:2016-09-08 11:40:21

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

我在互联网上搜索过的人,发现了很多将gridview导出为ex​​cel的解决方案。我尝试了所有的解决方案,但没有一个适合我。建议我跟踪 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 模块。

请帮帮我!!!

1 个答案:

答案 0 :(得分:1)

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

相关问题