GridView导出Excel加上样式并且去除超链接

来源:互联网 发布:网络端口怎么设置 编辑:程序博客网 时间:2024/06/07 07:12

GridView导出Excel加上样式并且去除超链接

        protected void BtnExcel_Click(object sender, EventArgs e)
        {
            Response.Clear();
            //Response.AddHeader("content-disposition", "attachment;filename=考核结果.xls");
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("考核结果.xls",Encoding.UTF8).ToString());
            Response.Charset = "gb2312";
            Response.ContentType = "application/ms-excel";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            GridView1.RenderControl(htmlWrite);

            string strExcel = stringWrite.ToString();

            //正则表达式,去除超链接,加个名称空间:System.Text.RegularExpressions;
            strExcel = Regex.Replace(strExcel, "<a (.*?)>", "", RegexOptions.Compiled);

            strExcel = Regex.Replace(strExcel, "</a>", "");

           //添加样式
            Response.Write(@"<style type='text/css'>
                                .width300{width:100px;}
                             </style>");
            Response.Write(strExcel);
            Response.End();
        }
        //如果没有下面方法会报错类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内
        public override void VerifyRenderingInServerForm(Control control)
        {


        }
0 0
原创粉丝点击