首页 > 代码库 > C# GridView 导出Excel表

C# GridView 导出Excel表

出错1:类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内
解决方案:在后台文件中重载VerifyRenderingInServerForm方法,如:
public override void VerifyRenderingInServerForm(Control control)
{
}

出错2:只能在执行 Render() 的过程中调用 RegisterForEventValidation(RegisterForEventValidation can only be called during Render();

解决方案:在源中,添加红色部分<%@ Page Language="C#" EnableEventValidation = "false"CodeFile="ExportGridView.aspx.cs" Inherits="ExportGridView" %>

另外,在使用时,把GRIDVIEW获取数据的方法getdata()写成public DataSet  getdata(),return 一个DS,

调用事件里,实例化一个DATASET, 让它值等于DS,

protected void btnExcel_Click(object sender, EventArgs e)        {            grid.AllowPaging = false;            grid.AllowSorting = false;            grid.Columns[7].Visible = false;            GridBindAll();            DateTime dt = DateTime.Now;            string str = dt.ToString("yyyyMMddhhmmss");            str = str + ".xls";            GridViewToExcel(grid, "application/ms-excel", str);            grid.AllowPaging = true;            grid.AllowSorting = true;            grid.Columns[2].Visible = true;            GridViewBind();            // Export(gvRecord, "application/ms-excel", str);        }        /// <summary>        /// 将网格数据导出到Excel        /// </summary>        /// <param name="ctrl">网格名称(如GridView1)</param>        /// <param name="FileType">要导出的文件类型(Excel:application/ms-excel)</param>        /// <param name="FileName">要保存的文件名</param>        public static void GridViewToExcel(Control ctrl, string FileType, string FileName)        {            HttpContext.Current.Response.Charset = "GB2312";            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;//注意编码            HttpContext.Current.Response.AppendHeader("Content-Disposition",                "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());            HttpContext.Current.Response.ContentType = FileType;//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword            ctrl.Page.EnableViewState = false;            StringWriter tw = new StringWriter();            HtmlTextWriter hw = new HtmlTextWriter(tw);            ctrl.RenderControl(hw);            HttpContext.Current.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />" + tw.ToString());            HttpContext.Current.Response.End();        }        public override void VerifyRenderingInServerForm(Control control)        {            //base.VerifyRenderingInServerForm(control);        }

 注意:只是导出了在GridView中的列,没有把数据库中的其它没有展示的列都导出。

C# GridView 导出Excel表