asp.net GridView导出到excel


asp.net GridView导出到excel

文章插图
首先呢 你得把你的数据绑定到一个GridView中 然后 下面的方法 就是导出了 。////// 将超链接、下拉框等样式去掉 ////// 【asp.net GridView导出到excel】 private void DisableControls(Control gv) { Literal l = new Literal(); string name = String.Empty; for (int i = 0; i < gv.Controls.Count; i++) { if (gv.Controls[i].GetType() == typeof(LinkButton)) { l.Text = (gv.Controls[i] as LinkButton).Text; gv.Controls.Remove(gv.Controls[i]); gv.Controls.AddAt(i, l); } else if (gv.Controls[i].GetType() == typeof(DropDownList)) { l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text; gv.Controls.Remove(gv.Controls[i]); gv.Controls.AddAt(i, l); } else if (gv.Controls[i].GetType() == typeof(HyperLink)) { l.Text = (gv.Controls[i] as HyperLink).Text; gv.Controls.Remove(gv.Controls[i]); gv.Controls.AddAt(i, l); } if (gv.Controls[i].HasControls()) { DisableControls(gv.Controls[i]); } } } ////// 将GridView中的内容导出成Excel文件 /// 如文件名为空,则使用规则生成文件默认 ////// 扩展名必须为xls,而不能是xlsx,否则不能直接在Excel中打开 public void ToExcel(string FileName) { if (string.IsNullOrEmpty(FileName)) { string filename = DateTime.Now.Ticks.ToString() + ".xls"; FileName = this.Parent.Page.Server.MapPath("~/Temp/" + filename); } //去除分页、排序 this.AllowPaging = false; this.AllowSorting = false; this.AutoDataBind(); //生成html this.DisableControls(this); HttpContext.Current.Response.Charset = "UTF-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; HttpContext.Current.Response.ContentType = "application/ms-excel"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName); this.Page.EnableViewState = false; System.IO.StringWriter tw = new System.IO.StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(tw); this.RenderControl(hw); string str = tw.ToString(); str = (Regex.Replace(str, @"()|", "", RegexOptions.IgnoreCase)); HttpContext.Current.Response.Write(str); HttpContext.Current.Response.End(); //还原分页、排序 this.AllowPaging = true; this.AllowSorting = true; this.AutoDataBind(); } #endregion

    推荐阅读