zoukankan      html  css  js  c++  java
  • 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);
        }

    完成后效果如下:

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

  • 相关阅读:
    java接口定义和作用
    8-12接口测试进阶-2源码分析
    接口测试3-4使用csv进行接口测试
    接口测试3-3Excel格式
    接口测试3-2csv格式
    java study2
    接口测试进阶3-1数据驱动测试
    java study1
    REST-assured 3发送图片
    codeforces 659C C. Tanya and Toys(水题+map)
  • 原文地址:https://www.cnblogs.com/qiu18359243869/p/13884980.html
Copyright © 2011-2022 走看看