码迷,mamicode.com
首页 > 其他好文 > 详细

gridview导出到excel

时间:2014-08-13 17:44:27      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   io   文件   

   public static void gvexcel(GridView grv, string strcells)
    {

        string style = @"<style> .text { mso-number-format:\@; } </script> ";//解决0缺失问题
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        HtmlTextWriter htw = new HtmlTextWriter(sw);     
        string fileName;
        #region 获得excel文件名称
        string year = DateTime.Now.Year.ToString();
        string month = DateTime.Now.Month.ToString();
        if (month.Length < 2) { month = "0" + month; }
        string day = DateTime.Now.Day.ToString();
        if (day.Length < 2) { day = "0" + day; }
        string hour = DateTime.Now.Hour.ToString();
        if (hour.Length < 2) { hour = "0" + hour; }
        string minute = DateTime.Now.Minute.ToString();
        if (minute.Length < 2) { minute = "0" + minute; }
        string second = DateTime.Now.Second.ToString();
        if (second.Length < 2) { second = "0" + second; }
        fileName = year + month + day + hour + minute + second;
        #endregion
        fileName += ".xls";

      
         Page page = new Page();
         page.EnableEventValidation = false;
         page.DesignerInitialize();
          HtmlForm form = new HtmlForm();
         page.Controls.Add(form);
         grv.AllowPaging = false;
         grv.AllowSorting = false;
         grv.EnableViewState = true;
         form.Controls.Add(grv);
         page.RenderControl(htw);
              
        //grv.RenderControl(htw);
       
     

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Buffer = true;
        HttpContext.Current.Response.ContentType = "applicationnd.ms-excel";
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename="+fileName+"");
        //HttpContext.Current.Response.Charset = "UTF-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//解决导出到Excel2007乱码问题         
        HttpContext.Current.Response.Write(style);
        HttpContext.Current.Response.Write(sb.ToString());
        HttpContext.Current.Response.End();
    }

 

gridview导出到excel,布布扣,bubuko.com

gridview导出到excel

标签:des   style   blog   http   color   os   io   文件   

原文地址:http://www.cnblogs.com/zhaolijing910/p/3910097.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!