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您的班级名称。
| 归档时间: |
|
| 查看次数: |
886 次 |
| 最近记录: |