ASP.NET中的GridView导出为EXCEL完整介绍

在将GridView导出为EXCEL时,有几个小技巧需要注意:

    1.  必须重载VerifyRenderingInServerForm函数

    public override void VerifyRenderingInServerForm(Control control)
    { }

   2. 导出函数如下:

         /// <summary>
        /// GridView导出为EXCEL
        /// </summary>
        /// <param >导出文件名</param>
        /// <param >gridview对象</param>
        /// <param >页对象</param>
        public static void ExportToExcel(string Filename, GridView gridview, Page page)
        {
            page.Response.ClearContent();
            page.Response.Buffer = true;
            page.Response.Charset = "";
            page.Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(Filename, System.Text.Encoding.UTF8) + ".xls");
            page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文
            page.Response.ContentType = "application/excel";
            page.EnableViewState = false;
            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
            System.IO.StringWriter sw = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
            gridview.RenderControl(htw);
            page.Response.Write(sw.ToString());
            page.Response.End();
        }

     

    函数引用:

    protected void ExcelButton_Click(object sender, EventArgs e)
    {
          DataSet ds = QueryDataDatas();
        if (ds == null)
            return;
        GridView2.DataSource = ds;
        GridView2.DataBind();
        ExportTo.ExportToExcel("Filename", GridView2, Page);
    }

   

   3. 如果含有类似于身份证这样的数据,在导出成为Excel后将变成科学计数法的形式显示,解决方法:可以通过以下方式进行转换,该段代码应写在RowDataBound事件中
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
         if (e.Row.RowType == DataControlRowType.DataRow)
             e.Row.Cells[2].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
    }

 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值