• gridview 导出到EXCEL


    最近想整理一些词库,懒得手动找,又怕手一哆嗦有遗漏,决定写程序完成吧。

    首先将数据用GridView控件显示到页面上,效果如下:

    接下来将GridView中的内容导出到Excel,方法如下:

     

     
     /// <summary>
        /// 由GridView导出Excel
        /// </summary>
        /// <param name="ctl">GridView控件ID</param>
        /// <param name="FileName">导出Excel名称</param>
        private void ToExcel(Control ctl, string FileName)
        {
            HttpContext.Current.Response.Charset = "UTF-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);
            ctl.Page.EnableViewState = false;
            System.IO.StringWriter tw = new System.IO.StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            ctl.RenderControl(hw);
            HttpContext.Current.Response.Write(tw.ToString());
            HttpContext.Current.Response.End();
        }
     

     

    在按钮上添加事件来导出Excel。注意,因为GridView是有分页和排序设置的,为了能够显示完整的数据,要先取消分页排序,导出之后再恢复设置。代码如下:

     

     
      protected void btnExport_Click(object sender, EventArgs e)
        {
            gvWord.AllowPaging = false;
            gvWord.AllowSorting = false;
            Display();
            ToExcel(gvWord, "word.xls");
            gvWord.AllowSorting = true;
            gvWord.AllowPaging = true;
            Display();
        }
     

     

    可是运行之后报错:

    类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内。

    添加重写方法:

     public override void VerifyRenderingInServerForm(Control control)
        {
            //base.VerifyRenderingInServerForm(control);
        }

    完成后效果如下:

    这下可以让程序帮我整理了,省了一笔麻烦啊。

  • 相关阅读:
    jdbc连接数据库
    UUID
    Oracle 查询
    JAVA开发工具eclipse中@author怎么改
    JAVA实现多线程入门
    JAVA编程中的类和对象
    为ubuntu操作系统增加root用户
    搭建Java环境JDK,和运行环境JRE
    安装Ubuntu14.04版本的操作系统
    Eclipse连接到My sql数据库之前操作
  • 原文地址:https://www.cnblogs.com/qiu18359243869/p/13884980.html
Copyright © 2020-2023  润新知