C# GridView 导出Excel表

Posted BrokenIce

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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表的主要内容,如果未能解决你的问题,请参考以下文章

C#实现GridView导出Excel

怎样将C#生成的数据导出

c#导出excel慢

c# 导入导出excel表格式

把GridView1的数据导出到excel的sheet1把GridView2的数据导出到excel的sheet2.

将 GridView 导出到 Excel 2007