.net導出excel出錯:只能在執行Render()的過程中調用Registerfor.........
在導出Excel的頁面修改:<%@page language="C#" EnableEventValidation="false"..............
//導出excel public void GridViewToExcel(GridView ExcelGridView, string FileName) { bool OldAllowPaging = ExcelGridView.AllowPaging; //处理分页:如果分页为True,则设置为False if (OldAllowPaging) ExcelGridView.AllowPaging = !OldAllowPaging; ExcelGridView.AllowSorting = false;
ExcelGridView.DataBind();// 重新绑定.
//有时用 gb2312 不能正常显示中文,要用 utf-8 //Response.Charset = "utf-8"; string style = @"<style> .text { mso-number-format:/@; } </style> "; Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); Response.Write("<meta http-equiv=Content-Type content=/"text/html; charset=utf-8/">"); //去除中文亂碼 //必要,做成下载文件 //Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
//如果要直接在浏览器中打开,把上行注释掉,换成下面这行 Response.ContentType = "application/vnd.ms-excel"; Response.Charset = ""; // 从Content-Type header中去除charset设置
//关闭 ViewState this.EnableViewState = false; System.IO.StringWriter tw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw); ExcelGridView.RenderControl(hw); //获取control的HTML Response.Write(style); Response.Write(tw.ToString()); //把HTML写回浏览器 Response.End(); ExcelGridView.AllowPaging = OldAllowPaging; ExcelGridView.AllowSorting = true; }
//用上面函數導出Excel時,必須用到這個函數 public override void VerifyRenderingInServerForm(Control control) { }
//匯出EXCEL protected void btnToExcel_Click(object sender, EventArgs e) { GridView1.DataSourceID = "odsGetCusComList"; GridViewToExcel(GridView1, ""); }