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);
        }

    完成后效果如下:

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

  • 相关阅读:
    超简单实例使用websocket进行server和client实时通信
    antd的table行key自增长
    selenium元素定位Xpath,Contains,CssSelector
    slenium使用鼠标+键盘事件或者双击实现代码
    使用python+pychram进行API测试(接口测试)初级STEP 1
    linux命令小常识
    sql中limit使用方法
    Swagger-API测试工具实战
    写 test-case心得
    测试之路之[前奏]
  • 原文地址:https://www.cnblogs.com/janes/p/1926161.html
Copyright © 2011-2022 走看看