All articles| All Pictures| All Softwares| All Video| Go home page| Write articles| Upload pictures

Reading number is top 10 articles
asp.net2.0,动态生成静态页并分页实例_[Asp.Net教程]
ASP.NET,3.5,Extensions新特性:ASP.NET,Dynamic,Data,体验2_[Asp.Net教程]
C#中PrintDocument组件的方法使用实例
细说数据库范式_mssql学习_编程技术
C#中HelpProvider组件应用实例
C#教程:C#2.0 新特性 局部类
基于AJAX技术提高搜索引擎排名_[AJAX教程]
HTML 初学者指南(4)_[Html教程]
动态网页变静态:ASP.NET生成静态HTML页_.net资料_编程技术
LINQ体验(17)——LINQ,to,SQL语句之动态查询_[Asp.Net教程]
Reading number is top 10 pictures
Chinese paper-cut grilles art appreciation5
一万二一支的万珂,用得真心肉疼。
Sora aoi mirror memorial classics1
非笑不可:最强爆笑图片精选
Photographed the passion of the clients and prostitutes in the sex trade picture1
yy365网站上的美女2
大人物的礼物
Born After 90 Beijing sports university campus flower photos1
红楼梦金陵十二钗(2)
随便发几张图
Download software ranking
asp.net技术内幕
Detective task-the top secret prostitution files
Call Of Duty2
Unix video tutorial14
Visual C++界面编程技术
Unix video tutorial9
Unix video tutorial8
Eclipse 4.2.2 For Win32
jdk1.6 for windows
Boxer's Top ten classic battle8
delv published in(发表于) 2014/1/23 3:11:35 Edit(编辑)
ASP.NET实例:手教你如何扩展GridView之自带Excel和Word导出_[Asp.Net教程]

ASP.NET实例:手教你如何扩展GridView之自带Excel和Word导出_[Asp.Net教程]

ASP.NET实例:手教你如何扩展GridView之自带Excel和Word导出_[Asp.Net教程]

在web应用程序中,我们是不是很发愁打印问题,您是不是有过为了打印写Activex的经历,我们有没有想过,Word和Excel的打印功能能被我们利用起来呢?只要我们将我们将数据导出到Excel或者Word中,打印岂不是小case了么。下面就谈谈如何让GridView自己支持导出Excel和Word 。
首先增加了两个属性,用于指示是否支持Excel导出和Word导出
//增加了一个设置是否显示“导出Word”按钮的属性
/**////


/// 排序提示信息
///

[
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;



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







添加到del.icio.us 添加到新浪ViVi 添加到百度搜藏 添加到POCO网摘 添加到天天网摘365Key 添加到和讯网摘 添加到天极网摘 添加到黑米书签 添加到QQ书签 添加到雅虎收藏 添加到奇客发现 diigo it 添加到饭否 添加到飞豆订阅 添加到抓虾收藏 添加到鲜果订阅 digg it 貼到funP 添加到有道阅读 Live Favorites 添加到Newsvine 打印本页 用Email发送本页 在Facebook上分享


Disclaimer Privacy Policy About us Site Map

If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)
Copyright ©2011-
uuhomepage.com, Inc. All rights reserved.