On my MVC 5 site, I have an export function to Excel that is stable, but users have requested that the column headers be “user friendly”.
In my model, I use annotations [Display(Name="Friendly Column Name")]and they appear as intended on the watch pages, but they are not transferred to the exported Excel file when the user launches the export function. Instead, true names appear.
I know that I can load sheet cells using a method other than LoadFromCollection , but I was wondering if it is possible to use LoadFromCollection and use the Display model (Name () Annotations).
This is what I have:
public ActionResult ExportToExcel(string _selectedCampus)
{
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)
.AsEnumerable();
byte[] response;
using (var excelFile = new ExcelPackage())
{
excelFile.Workbook.Properties.Title = "MIA 1A (i) Eligible FAY Students";
var worksheet = excelFile.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells["A1"]
.LoadFromCollection(Collection: exportQuery, PrintHeaders: true);
response = excelFile.GetAsByteArray();
}
return File(response, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Mia1aSec1Fay.xlsx");
}
The workaround is to overwrite the header cells, but this is undesirable for two reasons: (1) I already have the column names written as annotations in the model, which means that now I have the same information written in two different places, and (2) I need to manually synchronize the information if users want more changes, which I may have forgotten to do.
worksheet.Cells["A1"].LoadFromCollection(Collection: exportQuery, PrintHeaders: true);
worksheet.Cells[1, 1].Value = "Campus";
worksheet.Cells[1, 2].Value = "Student Name";
worksheet.Cells[1, 3].Value = "Credits Before SY";
worksheet.Cells[1, 4].Value = "Credits During Semester 1";
worksheet.Cells[1, 5].Value = "Legible Population";
worksheet.Cells[1, 6].Value = "Eligible Students Earning 2+ Credits";
It is written, I really hope that this is not the only option. There should be a way to write the display name values in the headers, not the true name.