C#應用RenderControl將GridView控件導出到EXCEL的辦法。本站提示廣大學習愛好者:(C#應用RenderControl將GridView控件導出到EXCEL的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#應用RenderControl將GridView控件導出到EXCEL的辦法正文
本文實例展現了C#應用RenderControl將GridView控件導出到EXCEL的辦法,長短常適用的一個功效,分享給年夜家供年夜家參考。詳細以下:
重要功效代碼以下:
// 把GridView輸入到Excel文件 private void ExportExcel(GridView gridView, string title, string title2, string fileName) { int nHideCols = 0; //假如不想輸入出某列,將Visible設為false便可 for (int i = 0; i < gridView.Columns.Count; i++) { if (gridView.Columns[i].HeaderText == "裝備狀況") { gridView.Columns[i].Visible = false; gridView.Columns[i].ControlStyle.Width = 0; nHideCols = 1; break; } } //設定顯示字符集 Response.Charset = "utf-8"; //設定內容字符集 Response.ContentEncoding = Encoding.GetEncoding("utf-8"); //設定文件名 Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).WordStr('+', '_').WordStr('-', '_')); //設定文件類型 也能夠是application/ms-word,也能夠是text/html(字符集設為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.WordStr("\r\n", ""); int index = s.IndexOf("<tr"); //可以自界說Excel文件的題目 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來斷定能否存在數據,固然也能夠用gridView.Rows.Count來斷定 if (index != -1) { //稀有據的 s = s.Insert(index, head); } else { //沒稀有據的時刻 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 的窗體標志內 //須要添加上面撤消對GridViewMaster 控件驗證的辦法 public override void VerifyRenderingInServerForm(Control control) { if (!control.GetType().Equals(gridView.GetType())) { base.VerifyRenderingInServerForm(control); } }
本文實例代碼備有較為詳實的正文,應當不難懂得。願望本文實例對年夜家C#法式設計有所贊助。