btnExport = new LinkButton();
 btnExport.CommandName = "ExportToExcel";
 btnExport.EnableViewState = true;
 btnExport.Text = "导出Excel";
 btnExportWord = new LinkButton();
 btnExportWord.CommandName = "ExportToWord";
 btnExportWord.EnableViewState = true;
 btnExportWord.Text = "导出Word";
 base.OnInit(e);
 }
将两个LinkButton添加到GridView子控件中。
 protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding) {
 int res = base.CreateChildControls(dataSource, dataBinding);
 try
 {
 GridViewRow row = new GridViewRow(0, 0, DataControlRowType.Pager, DataControlRowState.Normal); TableCell cell2 = new TableCell();
 cell2.HorizontalAlign = HorizontalAlign.Right;
 cell2.Wrap = false; if (this.ShowExportExcel == true)
 {
 l1 = new Literal();
 l1.Text = " [";
 cell2.Controls.Add(l1);
 cell2.Controls.Add(btnExport);
 l1 = new Literal();
 l1.Text = "] ";
 cell2.Controls.Add(l1);
 }
 if (this.ShowExportWord == true)
 {
 l1 = new Literal();
 l1.Text = " [";
 cell2.Controls.Add(l1);
 cell2.Controls.Add(btnExportWord);
 l1 = new Literal();
 l1.Text = "] ";
 cell2.Controls.Add(l1);
 } r.Cells.Add(cell2);
 this.Controls[0].Controls.AddAt(0, row);
 }
 catch
 {
 }
 }
 return res;
 }在导出的时候,我们希望一些列不被导出,如修改,删除这样的列,因此我们添加了这样的一个属性
用于指定不被导出列,列名之间用,隔开
 string _UnExportedColumnNames = "";
 [
 Description("不导出的数据列集合,将HeaderText用,隔开"),
 Category("扩展"),
 DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
 PersistenceMode(PersistenceMode.InnerProperty)
 ]
 public string UnExportedColumnNames
 {
 get
 {
 return _UnExportedColumnNames;
 }
 set
 {
 _UnExportedColumnNames = value;
 }
 }在导出的时候,原来的GridView列表中会有一些LinkButton或者DropDownList控件,导出的时候,我们也希望将其换成纯文本,用下面这个函数可以完成这个目的
用于将GridView中的LinkButton和DropDownList转换成文本的方法
 private void DisableControls(Control gv)
 {
 LinkButton lb = new LinkButton();
 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);
 }
 if (gv.Controls[i].HasControls())
 {
 DisableControls(gv.Controls[i]);
 }
 }
 }
下面是处理ItemCommand,将GridView导出的代码
处理OnRowCommand事件,将GridView数据导出到Excel和Word
 protected override void OnRowCommand(GridViewCommandEventArgs e)
 {
 base.OnRowCommand(e);
 if (e.CommandName == "ExportToExcel")
 {
 string[] ss = UnExportedColumnNames.Split(',');
 System.Collections.Generic.List list = new System.Collections.Generic.List();
 foreach (string s in ss)
 {
 if (s != ",")
 {
 list.Add(s);
 }
 }
 ShowToolBar = false;
 this.AllowSorting = false;
 HttpContext.Current.Response.Clear();
 HttpContext.Current.Response.AddHeader("content-disposition",
 "attachment;filename=" + ExcelFileName + ".xls");
 HttpContext.Current.Response.Charset = "GB2312";
 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
 HttpContext.Current.Response.ContentType = "application/ms-excel";
 System.IO.StringWriter stringWrite = new System.IO.StringWriter();
 System.Web.UI.HtmlTextWriter htmlWrite =
 new HtmlTextWriter(stringWrite);
 bool showCheckAll = ShowCheckAll;
 this.ShowCheckAll = false;
 this.AllowPaging = false;
 OnBind();
 DisableControls(this);
 foreach (DataControlField c in this.Columns)
 {
 if (list.Contains(c.HeaderText) && !string.IsNullOrEmpty(c.HeaderText))
 {
 c.Visible = false;
 }
 }
 this.RenderControl(htmlWrite);
 string content = System.Text.RegularExpressions.Regex.Replace(stringWrite.ToString(), "(]+>)|()", "");
 HttpContext.Current.Response.Write(content);
 HttpContext.Current.Response.End();
 this.AllowPaging = true;
 this.AllowSorting = true;
 ShowToolBar = true;
 this.ShowCheckAll = showCheckAll;
 OnBind();
 }
 else if (e.CommandName == "ExportToWord")
 {
 string[] ss = UnExportedColumnNames.Split(',');
 System.Collections.Generic.List list = new System.Collections.Generic.List();
 foreach (string s in ss)
 {
 if (s != ",")
 {
 list.Add(s);
 }
 }
 ShowToolBar = false;
 this.AllowSorting = false;
 HttpContext.Current.Response.Clear();
 HttpContext.Current.Response.AddHeader("content-disposition",
 "attachment;filename=" + ExcelFileName + ".doc");
 HttpContext.Current.Response.Charset = "GB2312";
 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
 HttpContext.Current.Response.ContentType = "application/ms-word";
 System.IO.StringWriter stringWrite = new System.IO.StringWriter();
 System.Web.UI.HtmlTextWriter htmlWrite =
 new HtmlTextWriter(stringWrite);
 bool showCheckAll = ShowCheckAll;
 this.ShowCheckAll = false;
 this.AllowPaging = false;
 OnBind();
 DisableControls(this);
 foreach (DataControlField c in this.Columns)
 {
 if (list.Contains(c.HeaderText) && !string.IsNullOrEmpty(c.HeaderText))
 {
 c.Visible = false;
 }
 }
 this.RenderControl(htmlWrite);
 string content = System.Text.RegularExpressions.Regex.Replace(stringWrite.ToString(), "(]+>)|()", "");
 HttpContext.Current.Response.Write(content);
 HttpContext.Current.Response.End();
 this.AllowPaging = true;
 this.AllowSorting = true;
 ShowToolBar = true;
 ShowCheckAll = showCheckAll;
 OnBind();
 }
 }
使用的时候,只要指定ShowExportExcel=True,ShowExportWord=True就自动出现导出Word和导出Excel的按钮了,点击自动会将GridView中的数据导出到Word或者Excel中了,如果原GridView是多页的,那也会自动将全部数据(而不是当前页的数据)导出,而且会剔除原来数据中的一些超级链接。使用起来相当简单,效果页非常好。
来源:jillzhang的blogs