【问题标题】:Epplus: How to make "LoadFromCollection" use [DisplayFormat()] attributes in modelEpplus:如何让“LoadFromCollection”在模型中使用 [DisplayFormat()] 属性
【发布时间】: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


【解决方案1】:

EPPlus 很遗憾没有实现对 DisplayFormat 的支持。

该库是开源的,因此您可以在 codeplex 上找到 LoadFromCollection 的完整实现及其重载

回答您的问题:恐怕您必须为此编写单独的代码。

【讨论】:

  • 确实如此,我使用 DisplayFormat 获得了标题
  • @AndersLindén EPPlus 仅查看 DescriptionAttribute 和 DisplayNameAttribute 并设置列标题。值按原样分配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多