如何使用作为LoadFromCollection的列标题

在我的MVC 5站点中,我有一个稳定的Export to Excel函数,但是用户要求我将列标题设置为“user friendly”。

在我的模型中,我使用[Display(Name="Friendly Column Name")]注释,并且它们按预期显示在视图页面上,但当用户触发导出function时不会导出到导出的Excel文件。 相反,真正的名字出现。

我知道我可以通过LoadFromCollection之外的其他方法加载工作表单元格,但我想知道是否仍然可以使用LoadFromCollection并使用模型的Display(Name())注解。

这是我现在有:

 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) .AsEnumerable(); // 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"); worksheet.Cells["A1"] .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", "Mia1aSec1Fay.xlsx"); } 

解决方法是覆盖标题单元格,但这是不受欢迎的,原因有两个:(1)我已经在模型中将列名称写为注释,这意味着我现在具有写在两个不同位置的相同信息, )我必须手动保持信息同步,以防用户需要更多的更改,而我可能会忘记这么做。

 // This loads teh table as seen by the user in the index view. worksheet.Cells["A1"].LoadFromCollection(Collection: exportQuery, PrintHeaders: true); // Workaround overwrite header cells, as I'm not able to use Display Name annotation. 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"; 

这是写的,我真的希望这不是唯一的select。 必须有一种方法来在报头中显示名称值,而不是真实的名称。

LoadFromCollection只响应DisplayNameDescription属性,而不是Display属性。

所以你可以尝试添加其中一个属性到你的当前属性。

 [DisplayName("Friendly Column Name")] [Display(Name = "Friendly Column Name")] public string StudentName { get; set; } 

还要确保在调用LoadFromCollection时将PrintHeaders参数设置为true,但是你说真正的名字出现了,所以这可能已经OK了。