导出到Excel时,如何将“显示名称”属性与GridView一起使用?

时间:2016-04-21 09:39:08

标签: c# asp.net-mvc gridview

我想在将List导出到Excel文件时使用[DisplayName()]属性设置Column标题文本。 任何解决方案?

GridView gv = new GridView();
gv.DataSource = ExportList;

gv.DataBind();

 System.Web.HttpContext.Current.Response.ClearContent();
 System.Web.HttpContext.Current.Response.Buffer = true;
 System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=Rapor.xls");
 System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
 System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
 System.Web.HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
System.Web.HttpContext.Current.Response.Output.Write(sw.ToString());
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();

1 个答案:

答案 0 :(得分:3)

您必须使用RowDataBound网格事件,如下所示: 首先在创建gv后放置这一行:

gv.RowDataBound+=GvOnRowDataBound;

然后按照以下代码:

private void GvOnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        for (int i = 0; i < e.Row.Cells.Count;i++)
        {
            var customAttributes =
                typeof (YourClass).GetProperty(e.Row.Cells[i].Text).CustomAttributes.ToList();
            var displayNameAttribute =
                customAttributes.FirstOrDefault(
                    aa => aa.AttributeType.FullName.Equals("System.ComponentModel.DisplayNameAttribute"));
            if (displayNameAttribute != null)
                e.Row.Cells[i].Text = displayNameAttribute.ConstructorArguments[0].ToString();
        }
    }
}

请记住将YourClass更改为您班级的名称。