This project has moved and is read-only. For the latest updates, please go here.

How can I use the [Display(Name="")] model attributes with LoadFromCollection?

Nov 24, 2015 at 8:51 PM
I am able to successfully load a worksheet with an IEnumerable in my controller function and the data exports correctly, but my users want the column titles to be "user-friendly". It turns out that even though I have [Display(Name="")] in annotations in my model, LoadFromCollection does not read those values -- instead, the true names of the columns are used.

Is there any way I can use LoadFromCollection and use the Display Name annotations?

This is what I currently have.
public ActionResult ExportToExcel(string _selectedCampus)
            // This is the query result set the user wishes to export to file
            IEnumerable<Mia1aSec1FayExport> exportQuery = unitOfWork
                .Mia1aSec1FayRepository.Get().Select(n => new Mia1aSec1FayExport
                Campus = n.Campus,
                StudentName = n.StudentName,
                CreditsBeforeSchoolYear = n.CreditsBeforeSchoolYear,
                CreditsDuringSemester1 = n.CreditsDuringSemester1,
                EligibleFayCount = n.EligibleFayCount,
                EligibleFayMeetingGoal = n.EligibleFayMeetingGoal
            }).Where(n => n.Campus == _selectedCampus).OrderBy(n => n.StudentName)

            // The current iteration saves the table contents, but without the 
            // [Display{Name"xxx)]annotation from the model.            
            byte[] response;   
            using (var excelFile = new ExcelPackage())
                excelFile.Workbook.Properties.Title = "MIA 1A (i) Eligible FAY Students";                
                var worksheet = excelFile.Workbook.Worksheets.Add("Sheet1");                   
                    .LoadFromCollection(Collection: exportQuery, PrintHeaders: true);
                response = excelFile.GetAsByteArray();

            // Save dialog appears through browser for user to save file as desired.
            return File(response, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", 
Nov 30, 2015 at 2:52 PM
Using [DisplayName("User-friendly name")] in the model worked perfectly. I needed to include using System.ComponentModel. Problem solved.