我在转换成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调用它时,我想构建一个动态网格视图来包含数据并将其导出。当我这样做的时候,我会从类中的Response.End调用中得到一个ThreadAbortException。
问题1:当我在一个用户控件中调用相同的代码时,为什么我得不到这个ThreadAbortException?用户控件有自己的线程或其他类型的上下文吗?
通过搜索出现该ThreadAbortException时得到的错误,我尝试用ApplicationInstance.CompleteRequest()来替换它。当我这样做时,我不再得到ThreadAbortException,但这破坏了以前工作的用户控件-而不是结果产生的包含来自网格的数据的excel电子表格,它包含来自包含页面的超文本标记语言,而且无论如何它都很容易用一个空的catch来抑制这个错误。但是,它不能用动态生成的GridView修复直接调用,该代码会呈现一个javascript错误:“无法解析从服务器收到的消息。”
我很想了解这里到底发生了什么,但我需要的是结果,而不是理解。我尝试过的所有其他方法(datagrid而不是GridView,等等)都遇到了同样的问题,并且本质上都是一样的,就是“接管”当前的响应,并使用字符串写入器和htmlwriter将数据呈现为excel contentType的响应。由于这显然可以在用户控件的上下文中工作,所以我对直接调用它不能工作的原因束手无策。
发布于 2011-06-23 02:41:14
这个问题实际上与excel导出完全无关。“…”无法解析“错误是关键。从这些链接中,我得到了关键信息,即网格事件只导致部分回发事件:
http://forums.asp.net/t/1392827.aspx
http://forums.aspfree.com/net-development-11/gridview-footer-template-button-in-updatepanel-not-posting-back-236087.html
这解释了ThreadAbortException和“…”无法解析“错误。解决方案是将此代码添加到ImageButton的OnPreRender中:
protected void addTrigger_PreRender(object sender, EventArgs e)
{
if (sender is ImageButton)
{
ImageButton imgBtn = (ImageButton)sender;
ScriptManager ScriptMgr = (ScriptManager)this.FindControl("ScriptManager1");
ScriptMgr.RegisterPostBackControl(ImgBtn);
}
}发布于 2011-06-18 14:12:36
请尝试: HttpApplication.CompleteRequest() as per:http://www.c6software.com/codesolutions/dotnet/threadabortexception.aspx
他们讨论了额外的html被being。
发布于 2011-06-18 19:59:12
使用这个
Response.Clear()
Response.AddHeader("content-disposition", atchment;filename=fm_specification.xls")
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/vnd.xls"
Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter
Dim htmlwrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
GridView1.RenderControl(htmlwrite)
Response.Write(stringWrite.ToString)
Response.End()你可以使用gridview1代替div
dont forget to add this on your page
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Subhttps://stackoverflow.com/questions/6393651
复制相似问题