本文實例展示了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).Replace('+', '_').Replace('-', '_')); //設定文件類型 也可以是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.Replace("/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#程序設計有所幫助。
新聞熱點
疑難解答