zoukankan      html  css  js  c++  java
  • C#:GridView导出Excel,以及runat=server错误处理方法

    C#:GridView导出Excel,以及runat=server错误处理方法

    例如,你有个按钮需要点击它就会把当前显示导出Excel,按钮例子如下

    <asp:LinkButton ID="LinkToExcel" runat="server" OnClick="LinkToExcel_Click">导出报表</asp:LinkButton>

    双击按钮就会在语句中生成按钮方法,本例中就是红色字体部分,

    然后在后台把如下代码复制进去

        protected void LinkToExcel_Click(object sender, EventArgs e)
        {
            string style = @"<style> .text { } </script> ";
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "GB2312"; //请勿删除此行,否则会出现乱码
            Response.AppendHeader("Content-Disposition", "attachment; filename =NewFileName.xls");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");      //设置输出流为简体中文
            Response.ContentType = "application/ms-excel";                              //设置输出文件类型为excel文件
            this.EnableViewState = false;
            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            this.GridView1.RenderControl(oHtmlTextWriter);
            Response.Write(style);
            Response.Write(oStringWriter.ToString());
            Response.End();
        }

    //以下的代码务必要加在上面一段后面,

        public override void VerifyRenderingInServerForm(Control control)
        {
            // 覆盖VerifyRenderingInServerForm方法,非常重要,否则系统会报错
            //base.VerifyRenderingInServerForm(control);
        }

    //否则会出现错误:

    //Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.

  • 相关阅读:
    SCCM2012 R2实战系列之四:初始化配置
    SCCM 2012 R2实战系列之一:SQL安装
    hdu 1242(bfs)
    hdu 1728(bfs)
    hdu 1253(bfs)
    hdu 3661
    hdu 1072(bfs)
    AC模版
    hdu 1010(dfs)
    poj 3628(01_page, dfs)
  • 原文地址:https://www.cnblogs.com/kentyshang/p/2800186.html
Copyright © 2011-2022 走看看