我有一个绑定(bind)到 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();
这里有更多 details 和一个解决方法。
关于c# - 导出到excel时线程被中止?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/421199/