C#使用RenderControl將GridView控件導(dǎo)出到EXCEL的方法
更新時間:2014年08月25日 17:35:05 投稿:shichen2014
這篇文章主要介紹了C#使用RenderControl將GridView控件導(dǎo)出到EXCEL的方法,是C#應(yīng)用程序設(shè)計中非常實用的一個功能,需要的朋友可以參考下
本文實例展示了C#使用RenderControl將GridView控件導(dǎo)出到EXCEL的方法,是非常實用的一個功能,分享給大家供大家參考。具體如下:
主要功能代碼如下:
// 把GridView輸出到Excel文件 private void ExportExcel(GridView gridView, string title, string title2, string fileName) { int nHideCols = 0; //如果不想輸出出某列,將Visible設(shè)為false即可 for (int i = 0; i < gridView.Columns.Count; i++) { if (gridView.Columns[i].HeaderText == "設(shè)備狀態(tài)") { gridView.Columns[i].Visible = false; gridView.Columns[i].ControlStyle.Width = 0; nHideCols = 1; break; } } //設(shè)定顯示字符集 Response.Charset = "utf-8"; //設(shè)定內(nèi)容字符集 Response.ContentEncoding = Encoding.GetEncoding("utf-8"); //設(shè)定文件名 Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).Replace('+', '_').Replace('-', '_')); //設(shè)定文件類型 也可以是application/ms-word,也可以是text/html(字符集設(shè)為gb2312) Response.ContentType = "application/ms-excel"; this.EnableViewState = false; using (StringWriter tw = new StringWriter()) { using (HtmlTextWriter hell = new HtmlTextWriter(tw)) { gridView.AllowPaging = false; gridView.RenderControl(hell); string s = tw.ToString(); s = s.Replace("\r\n", ""); int index = s.IndexOf("<tr"); //可以自定義Excel文件的標(biāo)題 string head = "<tr><td colspan=\"" + (gridView.Columns.Count - nHideCols).ToString() + "\" style=\"text-align: center; height: 42px; font-size: 24px; font-weight: bolder; color: #000000;\">" + title + "</td></tr>" + "<tr><td colspan=\"" + (gridView.Columns.Count - nHideCols).ToString() + "\" style=\"text-align: center; height: 24px; font-size: 12px; color: #000000;\">" + title2 + "</td></tr>"; //使用Index來判斷是否存在數(shù)據(jù),當(dāng)然也可以用gridView.Rows.Count來判斷 if (index != -1) { //有數(shù)據(jù)的 s = s.Insert(index, head); } else { //沒有數(shù)據(jù)的時候 s = "<table cellspacing=\"0\" cellpadding=\"3\" rules=\"rows\" border=\"1\" id=\"" + gridView.ID + "\" style=\"background-color:White;border-color:#E7E7FF;border-width:1px;border-style:None;border-collapse:collapse;\">" + head + "</table>"; } Response.Write(s); Response.End(); } } } //同時vs2005,vs2003會報錯“類型“ExGridView”的控件“GridViewMaster”必須放在具有 runat=server 的窗體標(biāo)記內(nèi) //需要添加下面取消對GridViewMaster 控件驗證的方法 public override void VerifyRenderingInServerForm(Control control) { if (!control.GetType().Equals(gridView.GetType())) { base.VerifyRenderingInServerForm(control); } }
本文實例代碼備有較為詳盡的注釋,應(yīng)該不難理解。希望本文實例對大家C#程序設(shè)計有所幫助。
相關(guān)文章
insert語句太長用StringBuilder優(yōu)化一下
insert語句太長用StringBuilder優(yōu)化一下,下面是示例代碼,需要的朋友可以研究研究2014-07-07C#使用Sleep(Int32)方法實現(xiàn)動態(tài)顯示時間
這篇文章主要為大家詳細(xì)介紹了C#如何使用Sleep(Int32)方法實現(xiàn)動態(tài)顯示時間,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,有需要的小伙伴可以參考下2024-01-01