导出到 Excel 时,如何将“显示名称”属性与网格视图一起使用

本文关键字:属性 显示名称 网格 一起 视图 显示 Excel | 更新日期: 2024-10-25 12:26:11

我想在

将列表导出到 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();

导出到 Excel 时,如何将“显示名称”属性与网格视图一起使用

您必须像这样使用网格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更改为类的名称。