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

datalist 导出excel的一个错误,指点一下
Response.Clear();
  Response.BufferOutput = true;
  Response.Charset = "GB2312";
  Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
  Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
  Response.ContentType = "application/ms-excel";
  this.EnableViewState = false;
  //System.Globalization.CultureInfo myCItrad =new System.Globalization.CultureInfo("ZH-CN", true);myCItrad
  StringWriter tw = new StringWriter();
  HtmlTextWriter hw = new HtmlTextWriter(tw);
  DataList3.RenderControl(hw );
  Response.Write(tw.ToString());
  Response.End();  

错误是——“只能在执行 Render() 的过程中调用 RegisterForEventValidation;”

------解决方案--------------------
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();

Response.AddHeader("content-disposition",
"attachment;filename=FileName.xls");

Response.Charset = "";

// If you want the option to open the Excel file without saving than

// comment out the line below

// Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.ContentType = "application/vnd.xls";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();

System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);

// turn off paging 
GridView1.AllowPaging = false;
BindData(); 


GridView1.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());

Response.End();

// turn the paging on again 
GridView1.AllowPaging = true;
BindData();

}