当前位置:首页 > ASP.NET实例:手教你如何扩展GridView之自带Excel和Word导出

ASP.NET实例:手教你如何扩展GridView之自带Excel和Word导出

点击次数:1265  更新日期:2010-12-27
\n

在web应用程序中,我们是不是很发愁打印问题,您是不是有过为了打印写Activex的经历,我们有没有想过,Word和Excel的打印功能能被我们利用起来呢?只要我们将我们将数据导出到Excel或者Word中,打印岂不是小case了么。下面就谈谈如何让GridView自己支持导出Excel和Word 。
首先增加了两个属性,用于指示是否支持Excel导出和Word导出
//增加了一个设置是否显示“导出Word”按钮的属性
/**//// <summary>
/// 排序提示信息
/// </summary>
[
Description("显示导出到Word"),
Category("扩展"),
DefaultValue(true)
]
public virtual bool ShowExportWord
{
get
{
object obj2 = this.ViewState["ShowExportWord"];
if (obj2 != null)
{
return (bool)obj2;
}
return true;
}
set
{
bool aShowExportWord = this.ShowExportWord;
if (value != aShowExportWord)
{
this.ViewState["ShowExportWord"] = value;
if (base.Initialized)
{
base.RequiresDataBinding = true;
}
}
}
}
//增加了一个设置是否显示“导出Excel”按钮的属性
[
Description("显示导出到Excel"),
Category("扩展"),
DefaultValue(true)
]
public virtual bool ShowExportExcel
{
get
{
object obj2 = this.ViewState["ShowExportExcel"];
if (obj2 != null)
{
return (bool)obj2;
}
return true;
}
set
{
bool aShowExportExcel = this.ShowExportExcel;
if (value != aShowExportExcel)
{
this.ViewState["ShowExportExcel"] = value;
if (base.Initialized)
{
base.RequiresDataBinding = true;
}
}
}
}声明两个LinkButton控件btnExportWord,btnExport,分别用于点击导出Excel和点击导出word,并在控件的OnInit事件中初始化两个控件
声明两个LinkButton,并在控件的OnInit中初始化
LinkButton btnExportWord;
LinkButton btnExport; protected override void OnInit(EventArgs e)
{
this.EnableViewState = true;


\n


btnExport = new LinkButton();
btnExport.CommandName = “ExportToExcel”;
btnExport.EnableViewState = true;
btnExport.Text = “导出Excel”;


\n

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);
}


\n

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)


\n

]
public string UnExportedColumnNames
{
get
{
return _UnExportedColumnNames;
}
set
{
_UnExportedColumnNames = value;
}
}在导出的时候,原来的GridView列表中会有一些LinkButton或者DropDownList控件,导出的时候,我们也希望将其换成纯文本,用下面这个函数可以完成这个目的
用于将GridView中的LinkButton和DropDownList转换成文本的方法
private void DisableControls(Control gv)
{


\n

LinkButton lb = new LinkButton();


\n

Literal l = new Literal();


\n

string name = String.Empty;


\n

for (int i = 0; i < gv.Controls.Count; i++)
{


\n

if (gv.Controls[i].GetType() == typeof(LinkButton))
{


\n

l.Text = (gv.Controls[i] as LinkButton).Text;


\n

gv.Controls.Remove(gv.Controls[i]);


\n

gv.Controls.AddAt(i, l);


\n

}
else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;


\n

gv.Controls.Remove(gv.Controls[i]);


\n

gv.Controls.AddAt(i, l);


\n

}


\n

if (gv.Controls[i].HasControls())
{
DisableControls(gv.Controls[i]);
}


\n

}
}
下面是处理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<string> list = new System.Collections.Generic.List<string>();


\n

foreach (string s in ss)
{
if (s != “,”)
{
list.Add(s);
}
}
ShowToolBar = false;
this.AllowSorting = false;
HttpContext.Current.Response.Clear();


\n

HttpContext.Current.Response.AddHeader(“content-disposition”,
“attachment;filename=” + ExcelFileName + “.xls”);


\n

HttpContext.Current.Response.Charset = “GB2312″;
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(“GB2312″);//设置输出流为简体中文
HttpContext.Current.Response.ContentType = “application/ms-excel”;


\n


System.IO.StringWriter stringWrite = new System.IO.StringWriter();


\n

System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);


\n

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(), “(<a[^>]+>)|(</a>)”, “”);
HttpContext.Current.Response.Write(content);


\n

HttpContext.Current.Response.End();


\n

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<string> list = new System.Collections.Generic.List<string>();


\n

foreach (string s in ss)
{
if (s != “,”)
{
list.Add(s);
}
}
ShowToolBar = false;
this.AllowSorting = false;
HttpContext.Current.Response.Clear();


\n

HttpContext.Current.Response.AddHeader(“content-disposition”,
“attachment;filename=” + ExcelFileName + “.doc”);


\n

HttpContext.Current.Response.Charset = “GB2312″;
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(“GB2312″);//设置输出流为简体中文
HttpContext.Current.Response.ContentType = “application/ms-word”;


\n


System.IO.StringWriter stringWrite = new System.IO.StringWriter();


\n

System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);


\n

bool showCheckAll = ShowCheckAll;
this.ShowCheckAll = false;
this.AllowPaging = false;
OnBind();


\n

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(), “(<a[^>]+>)|(</a>)”, “”);
HttpContext.Current.Response.Write(content);


\n

HttpContext.Current.Response.End();


\n

this.AllowPaging = true;
this.AllowSorting = true;
ShowToolBar = true;
ShowCheckAll = showCheckAll;
OnBind();
}
}
使用的时候,只要指定ShowExportExcel=True,ShowExportWord=True就自动出现导出Word和导出Excel的按钮了,点击自动会将GridView中的数据导出到Word或者Excel中了,如果原GridView是多页的,那也会自动将全部数据(而不是当前页的数据)导出,而且会剔除原来数据中的一些超级链接。使用起来相当简单,效果页非常好。


\n

来源:jillzhang的blogs

\n