C#导出到excel

来源:互联网 发布:顾城英儿里面的性 知乎 编辑:程序博客网 时间:2024/05/17 00:56

#region btnDetailData_Click
  /// <summary>
  /// 导出数据资料到excel中 add by fuxiding 20090622
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void btnDetailData_Click(object sender, System.EventArgs e)
  {
   try
   {
    //Period栏位必填
    if (this.ddlPeriod.SelectedValue.Equals(string.Empty))
    {
     UIUtility.Alert("Please choose the period!",this.Page);
     return;
    }

    //获取页面上查询栏位的值
    string sPeriod = this.ddlPeriod.SelectedValue;
    string sSite = this.txtSite.Text.Trim();
    string sBU = string.Empty;
    if (!this.ddlBU.SelectedValue.Equals(string.Empty))
    {
     sBU = "'" + this.ddlBU.SelectedValue + "'";
    }

    D01_Shipping_by_sizeManager ShipBySizeManager=new D01_Shipping_by_sizeManager();
    //获取需要导出的资料
    DataTable dt = ShipBySizeManager.GetExcelData(sPeriod,sSite,sBU);

    if (dt == null || dt.Rows.Count == 0)
    {
     UIUtility.Alert("No data,you can not export data!",this.Page);
     return;
    }
    
    DataGrid dgd=new DataGrid();
    dgd.DataSource=dt.DefaultView;
    dgd.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgd_ItemDataBound);
    dgd.DataBind();
    this.Response.Clear();  
    this.Response.AppendHeader("Content-Disposition", "attachment; filename="+DateTime.Today.Year+DateTime.Today.Month+DateTime.Today.Day+"D01ShippingReport.xls");
    this.Response.Charset="UTF7";  //输出的字符集
    this.Response.ContentEncoding =System.Text.Encoding.UTF7;  //编码类型
    Response.ContentType = "application/vnd.ms-excel";   //输出Excel  
    System.IO.StringWriter tw=new System.IO.StringWriter();
    HtmlTextWriter hw =new HtmlTextWriter(tw);   
    dgd.Visible= true;
    dgd.RenderControl(hw);
    dgd.Visible= false;
    this.Response.Write(tw.ToString());
    this.Response.End();

   }
   catch(Exception ex)
   {
     }
  }
  #endregion

原创粉丝点击