3

I have an ActionResult (in an MVC 5 website) that successfully uses Epplus to export a data set to an Excel document.

In the ActionResult code block, I use code like this to format the column as a short date. WIthout this code, the date column appears as int values.

// format date columns as date
worksheet.Column(6).Style.Numberformat.Format =
    DateTimeFormatInfo.CurrentInfo.ShortDatePattern;

However, in the Model, I already have this defined as an attribute. It works great on the View page, but doesn't format the column as a short date -- hence, the code shown above.

[Column(TypeName = "date")]
[DisplayName("Exit Date")]
**[DisplayFormat(DataFormatString = "{0:d}")]**
public DateTime ExitDate { get; set; }

To provide further context, I load my worksheet from a collection.

worksheet.Cells["A5"].LoadFromCollection(Collection: exportQuery, PrintHeaders: true);

Is there a way that I can extend LoadFromCollection so that that the worksheet not only loads the Collection content, but also the formatting attributes that exist in the model? The "DisplayName" attributes are collected, so is there a way to also collect "DisplayFormat" attributes without having to write separate code?

  • Its a bit unclear what you want to do or ow you want to use it, but you can use reflection to return a formatted value based on the `DisplayFormatAttribute`, for example `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); }` –  Dec 10 '15 at 22:31
  • I clarified my question. I'm trying to have "LoadFromCollection" format each column based on any existing DisplayFormat attributes, as it already names the column titles where DisplayName attributes exist in the model. –  Dec 10 '15 at 23:55

1 Answers1

4

EPPlus unfortunately didn't implement support for DisplayFormat.

The library is open source, so you can find the full implementation of LoadFromCollection and its overloads on codeplex

To answer you question: I'm afraid you will have to write separate code for this.

Philip Bijker
  • 4,955
  • 2
  • 36
  • 44