日期:2014-05-18  浏览次数:20497 次

由GridView导出Excel而引发的问题,帮忙解决下
protected void BindToGet()
  {
   
  BLL.YhgluserBLL bll=new BLL.YhgluserBLL();
  DataSet ds=bll.GetList(Global.strloginBMID);
  GV_User.DataSource = ds.Tables[0];
  GV_User.DataBind();
  ViewState["ds"] = ds;
  }
 protected void btnExcel_Click(object sender, EventArgs e)
  {
  DataSet ds =(DataSet) ViewState["ds"];
  GV_User.DataSource = ds.Tables[0];
  GV_User.DataBind();
  ToExcel();
  }

/// <summary>
  /// 使用ajax控件时,导出Excel必须加上该方法,解除服务器验证
  /// </summary>
  protected void Page_Init()
  {
  //PostBackTrigger trigger = new PostBackTrigger();
  //trigger.ControlID = ((Button)UpdatePanel1.FindControl("btnExcel")).UniqueID;
  //UpdatePanel1.Triggers.Add(trigger);
  //如果此处出错“无法找到触发器上的***ID”,也可直接在属性中给UpdatePanel设置PostBackTrigger的控件为Button的ID
  //方便起见,建议直接给UpdatePanel设置PostBackTrigger属性的控件为Button的ID,请看页面UpdatePanel的属性Triggers的PostBackTrigger

  我是在用户控件Yhgluser.ascx上设置了UpdatePanel属性Triggers的行为ControlID:btnExcel;EventName:Click;
  }

 /// <summary>
  /// 将GridView1的数据导出至Excel
  /// </summary>
  public void ToExcel()
  {
  HttpResponse response = HttpContext.Current.Response;
  response.Clear();
  response.Buffer = true;
  response.ContentType = "application/ms-excel";
  response.AddHeader("Content-Disposition", "attachment;filename=FileName.xls");
  response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
  response.Charset = "gb2312";
   
  EnableViewState = false;
  System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
  System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
  (UpdatePanel1.FindControl("GV_User") as GridView).RenderControl(oHtmlTextWriter);
   
  response.Write(oStringWriter.ToString());

  response.End();
  }

而我把 EnableEventValidation = "false" 和 
public override void VerifyRenderingInServerForm(Control control)
  {
  // base.VerifyRenderingInServerForm(control);  
  }
都写在了Yhgluser.aspx的页面上


小弟大部份的程式都會使用UserControl,而今在UserControl上使用了Ajax控件,在做GridView导出Excel时报出来的错误是:
Microsoft JScript 运行时错误: Sys.WebForms.PageRequestManagerParserErrorException: 无法分析从服务器收到的消息。之所以出现此错误,常见的原因是: 在通过调用 Response.Write() 修改响应时,将启用响应筛选器、HttpModule 或服务器跟踪。
详细信息: 分析附近的“<div>
<table cells”时出错。

怎么解决啊?

------解决方案--------------------
关注
------解决方案--------------------
把btnExcel按钮放在UpdatePanel外面,不要放在里面
如果能去掉ScriptManager 和 UpdatePanel 更好
------解决方案--------------------
这是老外给的解决方法:
There are a number of ways of doing this:

1.The easiest is to simply place the button outside of any UpdatePanels. Unfortunately the layout of your page might not allow for this.
2.Add a PostBackTrigger to your UpdatePanel that points at the button. This works great if the button is declared statically through markup on the page.
3.Call ScriptManager.RegisterPostBackControl() and pass in the button in questio