GridView在C#中匯出Excel的方法執行個體

來源:互聯網
上載者:User
本篇文章主要介紹了C#實現GridView匯出Excel執行個體代碼,這裡整理了詳細的代碼,非常具有實用價值,需要的朋友可以參考下。

using System.Data;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.IO;using System.Text;namespace DotNet.Utilities{ /// <summary> /// Summary description for GridViewExport /// </summary> public class GridViewExport {  public GridViewExport()  {   //   // TODO: Add constructor logic here   //  }  public static void Export(string fileName, GridView gv)  {   HttpContext.Current.Response.Clear();   HttpContext.Current.Response.AddHeader(    "content-disposition", string.Format("attachment; filename={0}", fileName));   HttpContext.Current.Response.ContentType = "application/ms-excel";   //HttpContext.Current.Response.Charset = "utf-8";   using (StringWriter sw = new StringWriter())   {    using (HtmlTextWriter htw = new HtmlTextWriter(sw))    {     // Create a form to contain the grid     Table table = new Table();     table.GridLines = GridLines.Both; //儲存格之間添加實線     // add the header row to the table     if (gv.HeaderRow != null)     {      PrepareControlForExport(gv.HeaderRow);      table.Rows.Add(gv.HeaderRow);     }     // add each of the data rows to the table     foreach (GridViewRow row in gv.Rows)     {      PrepareControlForExport(row);      table.Rows.Add(row);     }     // add the footer row to the table     if (gv.FooterRow != null)     {      PrepareControlForExport(gv.FooterRow);      table.Rows.Add(gv.FooterRow);     }     // render the table into the htmlwriter     table.RenderControl(htw);     // render the htmlwriter into the response     HttpContext.Current.Response.Write(sw.ToString());     HttpContext.Current.Response.End();    }   }  }  /// <summary>  /// Replace any of the contained controls with literals  /// </summary>  /// <param name="control"></param>  private static void PrepareControlForExport(Control control)  {   for (int i = 0; i < control.Controls.Count; i++)   {    Control current = control.Controls[i];    if (current is LinkButton)    {     control.Controls.Remove(current);     control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));    }    else if (current is ImageButton)    {     control.Controls.Remove(current);     control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));    }    else if (current is HyperLink)    {     control.Controls.Remove(current);     control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));    }    else if (current is DropDownList)    {     control.Controls.Remove(current);     control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));    }    else if (current is CheckBox)    {     control.Controls.Remove(current);     control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));    }    if (current.HasControls())    {     PrepareControlForExport(current);    }   }  }  /// <summary>  /// 匯出Grid的資料(全部)到Excel  /// 欄位全部為BoundField類型時可用  /// 要是欄位為TemplateField模板型時就取不到資料  /// </summary>  /// <param name="grid">grid的ID</param>  /// <param name="dt">資料來源</param>  /// <param name="excelFileName">要匯出Excel的檔案名稱</param>  public static void OutputExcel(GridView grid, DataTable dt, string excelFileName)  {   Page page = (Page)HttpContext.Current.Handler;   page.Response.Clear();   string fileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(excelFileName));   page.Response.AddHeader("Content-Disposition", "attachment:filename=" + fileName + ".xls");   page.Response.ContentType = "application/vnd.ms-excel";   page.Response.Charset = "utf-8";   StringBuilder s = new StringBuilder();   s.Append("<HTML><HEAD><TITLE>" + fileName + "</TITLE><META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>");   int count = grid.Columns.Count;   s.Append("<table border=1>");   s.AppendLine("<tr>");   for (int i = 0; i < count; i++)   {    if (grid.Columns[i].GetType() == typeof(BoundField))     s.Append("<td>" + grid.Columns[i].HeaderText + "</td>");    //s.Append("<td>" + grid.Columns[i].HeaderText + "</td>");   }   s.Append("</tr>");   foreach (DataRow dr in dt.Rows)   {    s.AppendLine("<tr>");    for (int n = 0; n < count; n++)    {     if (grid.Columns[n].Visible && grid.Columns[n].GetType() == typeof(BoundField))      s.Append("<td>" + dr[((BoundField)grid.Columns[n]).DataField].ToString() + "</td>");    }    s.AppendLine("</tr>");   }   s.Append("</table>");   s.Append("</body></html>");   page.Response.BinaryWrite(System.Text.Encoding.GetEncoding("utf-8").GetBytes(s.ToString()));   page.Response.End();  } }}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.