导出excel

一 把GridView或DataGrid在页面中呈现的内容导出
      public static void ToExcel(System.Web.UI.Control ctl)
  {
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
        HttpContext.Current.Response.Charset = "UTF-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
        HttpContext.Current.Response.ContentType = "application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-            excel/msword 
         ctl.Page.EnableViewState = false;
         System.IO.StringWriter tw = new System.IO.StringWriter();
         System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
         ctl.RenderControl(hw);
         HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();
    } 
   直接使用上面的方法会出错‘类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内‘, 在页面中加入下面代码则可以顺利通过编译,实现导出功能
   public override void VerifyRenderingInServerForm(Control control)
    { }

你可能感兴趣的:(导出Excel)