【发布时间】:2015-12-10 19:01:53
【问题描述】:
我有一个 ActionResult(在 MVC 5 网站中),它成功使用 Epplus 将数据集导出到 Excel 文档。
在 ActionResult 代码块中,我使用这样的代码将列格式化为短日期。如果没有此代码,日期列将显示为 int 值。
// format date columns as date
worksheet.Column(6).Style.Numberformat.Format =
DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
但是,在模型中,我已经将其定义为属性。它在“查看”页面上效果很好,但不会将该列格式化为短日期 - 因此,上面显示的代码。
[Column(TypeName = "date")]
[DisplayName("Exit Date")]
**[DisplayFormat(DataFormatString = "{0:d}")]**
public DateTime ExitDate { get; set; }
为了提供更多上下文,我从一个集合中加载我的工作表。
worksheet.Cells["A5"].LoadFromCollection(Collection: exportQuery, PrintHeaders: true);
有没有一种方法可以扩展 LoadFromCollection,以便工作表不仅可以加载 Collection 内容,还可以加载模型中存在的格式属性?收集了“DisplayName”属性,那么有没有办法也可以收集“DisplayFormat”属性而无需编写单独的代码?
【问题讨论】:
-
有点不清楚你想做什么或者你想使用它,但是你可以使用反射返回一个基于
DisplayFormatAttribute的格式化值,例如public string GetFormattedDate(YourModel model) { PropertyInfo pi = model.GetType().GetProperty("ExitDate"); DisplayFormatAttribute att = (DisplayFormatAttribute)pi.GetCustomAttributes(typeof(DisplayFormatAttribute), true).FirstOrDefault(); return string.Format(att.DataFormatString, model.ExitDate); } -
我澄清了我的问题。我正在尝试根据任何现有的 DisplayFormat 属性对每列进行“LoadFromCollection”格式化,因为它已经命名了模型中存在 DisplayName 属性的列标题。
标签: c# asp.net-mvc excel epplus