控件 数据下载 导出

来源:互联网 发布:ipadair2清理垃圾软件 编辑:程序博客网 时间:2024/05/16 23:42
 

public class Common  
{  
  #region --下载控件内容到 Excel  
  /// <summary>  
  /// 下载控件内容到,Excel 文件  
  /// </summary>  
  /// <param name="response">Response 引用</param>  
  /// <param name="con">父控件,接受子控件的引用(GridView , DataList , Repeater)</param>  
  /// <param name="fileName">下载文件名</param>  

  public static string DownLoadControlAsExcel(HttpResponse response, Control con, string fileName)  
  {  
  try  
  {  
  //设置文件名,及下载格式  
  response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");  
  response.ContentType = "application/vnd.ms-excel";  
  response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");  
  //this.EnableViewState = false;  
  System.IO.StringWriter strWriter = new System.IO.StringWriter();  
  System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(strWriter);  
  //设置到处内容控件(Anyone 父类Control即可)  
  con.RenderControl(hw);  

  response.Write(strWriter.ToString());  

  //释放资源  
  strWriter.Dispose();  

  hw.Dispose();  

  response.End();  
  return null;  

  }  
  catch  
  {  
  return "下载数据到Excel异常。";  

  }  
  }  
  #endregion  
}

原创粉丝点击