这几天工作中碰到一个问题,将GridView列表以Excel形式导出。
但是我们构造GridView列表的时候,遇到长的内容字符串,一般都会用一个字符串方法截断一下,这样用Excel导出的内容,就不是客户希望的全部内容了。例如:“我们的内容” 被截断后得到 “我们的...”。
那么希望在导出Excel前替换掉这个列,换成全文显示的绑定列。
一般的BoundField的绑定方法请参看我博客的文章“GridView动态绑定列”。
本文只涉及TemplateField的构造方法,而且只针对前台页面为 下面代码样式的情况
<asp:TemplateField HeaderText="地址" SortExpression="Address">
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Eval("NC_cruisePersonInfo.Address") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
完成此效果分为两步:
1. 先构造一个自定义的TemplateField类
public class MyTemplate : ITemplate
{
//设定列的绑定字符串
protected string bindColname;
public MyTemplate(){}
public MyTemplate(string bindCname)
{
//通过构造函数得到此绑定字符串
bindColname = bindCname;
}
//初始化函数,类初始化时候自动调用
public void InstantiateIn(System.Web.UI.Control container)
{
//构造一个lable
Label lblDisplay = new Label();
//添加此lable的绑定方法
lblDisplay.DataBinding += new EventHandler(this.Lable_DataBinding);
//将此lable加到TemplateField容器中
container.Controls.Add(lblDisplay);
}
//lable绑定方法
private void Lable_DataBinding(Object sender, EventArgs e)
{
//得到要绑定的lable
Label l = (Label)sender;
GridViewRow row = (GridViewRow)l.NamingContainer;
//这句最重要---此列的行绑定形式为Eval,绑定内容为bindColname
l.Text = DataBinder.Eval(row.DataItem, bindColname).ToString();
}
}
2. 页面后台文件中绑定至GridView
TemplateField remarkField = new TemplateField();
//构造自定义的TemplateField类对象
MyTemplate t2 = new MyTemplate("NC_cruisePersonInfo.Address");
//设定列标题
addressField.HeaderText = "地址";
//将此Template加入到TemplateField中
addressField.ItemTemplate = t2;
//插入到GridView的列中
gvCruisePerson.Columns.Insert(8,addressField);
经由这两步,就动态的为GridView绑定了一个TemplateField 得列,此列的内容表达为 NC_cruisePersonInfo.Address ,其中NC_cruisePersonInfo是GridView对象数据源,实体对象的一个“类”属性。
本文介绍如何在ASP.NET中解决GridView导出Excel时部分内容被截断的问题,通过自定义TemplateField实现完整内容的显示。
205

被折叠的 条评论
为什么被折叠?



