将DataGrid内容生成标准的Excel格式文件(无组件版)

///


  /// 导出Excel
  ///

  ///
  /// DataTable数据集
  public static void ExportExcel(System.Web.UI.Page page,System.Data.DataTable dtTable)
  {
   System.Web.UI.WebControls.DataGrid dgdGrid=new System.Web.UI.WebControls.DataGrid();
   dgdGrid.DataSource = dtTable.DefaultView;
   dgdGrid.AllowPaging = false;
   DataColumn dc = new DataColumn();
   dgdGrid.DataBind();

   page.Response.Clear();
   page.Response.Buffer= true;
   page.Response.Charset="utf-8";   
   page.Response.AppendHeader("Content-Disposition","attachment;filename=FileName.xls"); //FileName.xls
   page.Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文
   page.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
   page.EnableViewState = false;   
   System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo( "ZH-CN",true);
   System.IO.StringWriter oStringWriter = new System.IO.StringWriter( myCItrad);

   System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

   dgdGrid.RenderControl(oHtmlTextWriter);
   page.Response.Write(oStringWriter.ToString());
   page.Response.End();

  }

 

你可能感兴趣的:(WebDev,WEB开发及技术支持)