尝试将数据网格导出为ex​​cel,执行到Global axax中的Application_Error

我在互联网search的人,发现很多解决scheme出口gridview到Excel。 我尝试了所有的解决scheme,但没有一个为我工作。 build议我跟踪Application_Error模块。

当debugging我的执行去

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

我得到的exception是:: exception的types'System.Web.HttpUnhandledException'被抛出。

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

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

在debugging的时候,我没有得到任何exception,但是在执行这段代码之后,执行到Global.asax文件的Application_Error模块。

请帮帮我!!!

Server.GetLastError()是你的朋友 – 在Application_Error方法中使用它来获取最后遇到的exception,并看看你可以从中学到什么。 在这里寻找更多关于处理应用程序级错误的细节。