我遇到了转换为Excel代码的问题,我在找。我工作在.NET 4.0中一个网站项目,我创建了一个类此,做以下(基于 http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html):导出到Excel - ThreadAbortException
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition",
string.Format("attachment; filename={0}", fileName)); HttpContext.Current.Response.ContentType = "application/ms-excel"; using (StringWriter sw = new StringWriter()) {
using (HtmlTextWriter htw = new HtmlTextWriter(sw)) {
//Create a table to contain the grid
//Add header row
//Add each data row
//Add Footer row
//Render the table into the htmlwriter
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
我调用这个类从包含一个按钮是用户控件被添加到页面上显示的GridView中。这按预期工作 - 单击按钮,您将看到一个下载选项,用于打开或保存生成的包含GridView数据的Excel电子表格。
但是,当我从一个不同的GridView中的linkbutton调用它时,我想构建一个动态的gridview来包含数据并导出它。当我这样做时,我从类中的Response.End调用中得到一个ThreadAbortException。
问题1:为什么在调用usercontrol中的相同代码时没有得到该ThreadAbortException?用户控件是否有自己的线程或其他类型的上下文?
在发生ThreadAbortException时发生的错误搜索导致我尝试用ApplicationInstance.CompleteRequest()替换它。当我这样做时,我不再获得ThreadAbortException,但是这会打破以前工作的用户控件 - 而不是生成的包含网格数据的Excel电子表格,它包含来自包含页面的HTML,无论如何,它很容易压制这个错误与一个空的捕获。但是,它并没有修复动态生成的GridView的直接调用,该代码呈现出一个javascript错误:“从服务器收到的消息无法解析。”
我很想知道这里到底发生了什么,但我无论理解如何都需要结果。我尝试过的所有其他方法(数据网格而不是GridView等)都遇到了相同的问题,在涉及到“接管”当前响应并使用stringwriter和htmlwriter将数据转换为excel contentType的响应。而且,由于这明显符合UserControl的情况下工作,我在我束手无策,为什么时直接调用它不会工作...
可能的重复[为什么我的asp.net应用程序抛出ThreadAbortException?](http://stackoverflow.com/questions/12476/why-is-my-asp-net-application-throwing-threadabortexception) –
I don不相信这是重复的 - 这是一个非常具体的案例,处理两种情况 - 一种情况是发生了对response.end的调用,另一种情况下它并不支持 –