导出到Excel-ThreadAbortException
|
我发现转换为Excel代码时遇到问题。我正在.NET 4.0中的网站项目上工作,并且为此创建了一个类,该类可以执行以下操作(基于
http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html):
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:当从用户控件中调用相同的代码时,为什么没有得到ThreadAbortException?用户控件是否获得自己的线程或其他某种上下文?
搜索发生ThreadAbortException时得到的错误,导致我尝试用ApplicationInstance.CompleteRequest()替换它。当我这样做时,我不再得到ThreadAbortException,但是这破坏了以前正常工作的用户控件-而不是包含表格数据的excel电子表格,它包含了包含页面的HTML,无论如何它很容易足以通过空捕获来抑制该错误。但是,它不能解决动态生成的GridView的直接调用,该代码会呈现javascript错误:“无法解析从服务器收到的消息。”
我很想了解这里到底发生了什么,但是无论理解如何,我都需要结果。我尝试过的所有其他方法(使用数据网格而不是GridView等)都遇到相同的问题,并且在归结为“接管”时本质上相同。
当前响应,并使用stringwriter和htmlwriter将数据呈现为具有excel contentType的响应。而且由于这显然可以在用户控件的上下文中起作用,因此我直言不讳地解释了为什么直接调用它不起作用...
没有找到相关结果
已邀请:
4 个回复
茬贺努充尽
缮淳彼誊
可以使用div代替gridview1
扭湘阀柿蹄
视蕉梁拌客