导出到 Excel 时,如何在 GridView 中使用显示名称属性?

mor*_*now 3 c# asp.net-mvc gridview

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

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();
Run Code Online (Sandbox Code Playgroud)

小智 6

您必须RowDataBound像这样使用网格事件:在创建 gv 后首先放置此行:

gv.RowDataBound+=GvOnRowDataBound;
Run Code Online (Sandbox Code Playgroud)

然后按照这个代码:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢...它为我节省了很多时间。只是一些观察可以帮助其他人: 1 - 在调用 DataBind() 方法之前调用它。2 - 要从标题文本中删除 (") 将代码中的行替换为 -&gt; e.Row.Cells[i].Text = displayNameAttribute.ConstructorArguments[0].Value.ToString(); (2认同)