国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#實現GridView導出Excel實例代碼

2019-10-29 21:11:59
字體:
來源:轉載
供稿:網友

導出Excel在很多項目中經常用到,本人介紹了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();  } }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到c#教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 柞水县| 博客| 若尔盖县| 双流县| 双峰县| 大埔区| 南阳市| 梁河县| 青铜峡市| 杭州市| 隆安县| 年辖:市辖区| 秭归县| 上虞市| 凤城市| 贵州省| 巴林右旗| 梓潼县| 定州市| 临沭县| 顺平县| 兴国县| 昭平县| 葵青区| 通河县| 新安县| 长沙县| 称多县| 苗栗县| 富蕴县| 水富县| 津市市| 天台县| 汾阳市| 定结县| 灵宝市| 长宁区| 云霄县| 巩义市| 辛集市| 兰州市|