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

完成后效果如下:

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

原文地址:https://www.cnblogs.com/janes/p/1926161.html