[ 来源:www.it55.com | 作者: | 时间:2007-07-15 | 收藏 | 推荐 ] 【大 中 小】
在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)
{ IT资讯之家 www.it55.com
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"; www.it55.com
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); www.it55.com
l1 = new Literal();
l1.Text = "] ";
cell2.Controls.Add(l1);
} 免费资源www.it55.com
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),
(编辑:IT资讯之家 www.it55.com)