【发布时间】:2014-01-26 03:04:37
【问题描述】:
我尝试将我的数据集转换为 excel 并下载该 excel。我得到了所需的 excel 文件。但是每次下载 excel 时都会引发 System.Threading.ThreadAbortException。 如何解决这个问题?... 请帮帮我...
我在我的aspx屏幕中调用了这个方法。这个方法也抛出了同样的异常。
我在许多 aspx 屏幕中调用了 public void ExportDataSet(DataSet ds) 函数,并且我还在为运行时引发的异常维护错误记录器方法,这些异常被写入 .txt 文件。所以同样的异常记录在所有aspx屏幕的txt文件中。我只是想避免这个异常从方法声明的类文件抛出到aspx。只是我只想在我的方法声明类文件本身处理这个异常。
ASPX 文件方法调用: excel.ExportDataSet(dsExcel);
方法定义:
public void ExportDataSet(DataSet ds)
{
try
{
string filename = "ExcelFile.xls";
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "";
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
GridView dg = new GridView();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
// response.Write(style);
response.Write(sw.ToString());
response.End(); // Exception was Raised at here
}
}
}
catch (Exception ex)
{
string Err = ex.Message.ToString();
EsHelper.EsADLogger("HOQCMgmt.aspx ibtnExcelAll_Click()", ex.Message.ToString());
}
finally
{
}
}
【问题讨论】:
-
不要使用
Response.End见stackoverflow.com/a/3917180/2864740(和其他答案);请注意,该异常是“可以预料的”,因为它是堆栈展开的方式(因此不要捕获该异常)。如果您仍想捕获 [其他] 异常,请使用:.. catch (ThreadAbortException) { throw; /* propagate */ } catch (Exception ex) { .. } -
只是好奇你用的是什么记录器