我有一个绑定到GridView的DataTable.我还有一个按钮,单击时将DataTable导出到Excel文件.但是,发生以下错误:
ErrMsg ="线程正在中止."
以下是抛出错误的代码的一部分:
private static void Export_with_XSLT_Web(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName) { try { // Appending Headers HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; if(FormatType == ExportFormat.CSV) { HttpContext.Current.Response.ContentType = "text/csv"; HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } else { HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename=" + FileName); } // XSLT to use for transforming this dataset. MemoryStream stream = new MemoryStream(); XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8); CreateStylesheet(writer, sHeaders, sFileds, FormatType); writer.Flush(); stream.Seek(0, SeekOrigin.Begin); XmlDataDocument xmlDoc = new XmlDataDocument(dsExport); //dsExport.WriteXml("Data.xml"); XslTransform xslTran = new XslTransform(); xslTran.Load(new XmlTextReader(stream), null, null); using(StringWriter sw = new StringWriter()) { xslTran.Transform(xmlDoc, null, sw, null); //Writeout the Content HttpContext.Current.Response.Write(sw.ToString()); writer.Close(); stream.Close(); HttpContext.Current.Response.End(); } } catch(ThreadAbortException Ex) { string ErrMsg = Ex.Message; } catch(Exception Ex) { throw Ex; } finally { } }
改变HttpContext.Current.Response.End到HttpContext.Current.ApplicationInstance.CompleteRequest之后,它现在只是进入finally块,我无法弄清楚被抛出什么样的错误消息.
从以下行抛出ThreadAbortException:
HttpContext.Current.Response.End();
这里有更多细节和解决方法.
我试过用HttpContext.Current.ApplicationInstance.CompleteRequest
.它确实有效,但也在下载文件的末尾导出了页面的完整HTML代码,这是不可取的.
Response.BuffferOutput = True; Response.Flush(); Response.Close();
经过一番努力,我碰到了上面的代码.并且它在下载文件的末尾没有任何异常或不需要的代码,完美地工作.
资源