作者:webabcd
介绍
把GridView导出为一个Excel文件算是一个经常要用到的功能,也比较简单,我们来扩展一个GridView以实现这样的功能。
控件开发
1、新建一个继承自GridView的类。

/**//// <summary>
/// 继承自GridView
/// </summary>
[ToolboxData(@"<{0}:SmartGridView runat='server'></{0}:SmartGridView>")]
public class SmartGridView : GridView

{
}2、重写OnRowCommand,以实现把GridView导出为Excel的功能

/**//// <summary>
/// OnRowCommand
/// </summary>
/// <param name="e"></param>
protected override void OnRowCommand(GridViewCommandEventArgs e)
{
if (e.CommandName.ToLower() == "exporttoexcel")
{
System.Web.HttpContext.Current.Response.ClearContent();
// e.CommandArgument用“;”隔开两部分,左边的部分为导出Excel的文件名称
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + e.CommandArgument.ToString().Split(';')[0] + ".xls");
System.Web.HttpContext.Current.Response.ContentType = "application/excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
// e.CommandArgument用“;”隔开两部分,右边的部分为需要隐藏的列的索引(列索引用“,”分开)
if (e.CommandArgument.ToString().Split(';').Length > 1)
{
foreach (string s in e.CommandArgument.ToString().Split(';')[1].Split(','))
{
int i;
if (!Int32.TryParse(s, out i))
{
throw new ArgumentException("需要隐藏的列的索引不是整数");
}
if (i > this.Columns.Count)
{
throw new ArgumentOutOfRangeException("需要隐藏的列的索引超出范围");
}
this.Columns[i].Visible = false;
}
}
// 隐藏“导出Excel”按钮
((Control)e.CommandSource).Visible = false;
// 如果HeaderRow里的控件是button的话,则把它替换成文本
foreach (TableCell tc in this.HeaderRow.Cells)
{
// TableCell里的每个Control
foreach (Control c in tc.Controls)
{
// 如果控件继承自接口IButtonControl
if (c.GetType().GetInterface("IButtonControl") != null && c.GetType().GetInterface("IButtonControl").Equals(typeof(IButtonControl)))
{
// 如果该控件不是“导出Excel”按钮则把button转换成文本
if (!c.Equals(e.CommandSource))
{
tc.Controls.Clear();
tc.Text = ((IButtonControl)c).Text;
}
}
}
}
// 将服务器控件的内容输出到所提供的 System.Web.UI.HtmlTextWriter 对象中
this.RenderControl(htw);
System.Web.HttpContext.Current.Response.Write(sw.ToString());
System.Web.HttpContext.Current.Response.End();
}
base.OnRowCommand(e);
}