您的位置:首页 > 编程语言 > ASP

C# ASP.NET GridView导出EXCEL。

2014-09-10 16:15 501 查看
C# CODE:

using System.IO;

using System.Web.UI;

        public void GridViewToExcel(Control ctrl)

        {

            try

            {

                HttpContext.Current.Response.Charset = "GB2312";

                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;//注意编码

                HttpContext.Current.Response.AppendHeader("Content-Disposition",

                    "attachment;filename=" + HttpUtility.UrlEncode("CurrentTaskStates.xls", System.Text.Encoding.UTF8).ToString());

                HttpContext.Current.Response.ContentType = "application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 

                ctrl.Page.EnableViewState = false;

                StringWriter tw = new StringWriter();

                HtmlTextWriter hw = new HtmlTextWriter(tw);

                ctrl.RenderControl(hw);

                HttpContext.Current.Response.Write(tw.ToString());

                HttpContext.Current.Response.End();

            }

            catch

            {

                //log.WriteLog(ex);

                // return;

            }

        }

 public override void VerifyRenderingInServerForm(Control control)

        {

            //base.VerifyRenderingInServerForm(control);

        }///重载,这个一定要有。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# asp.net gridview excel