如何使用 [Display(Name="")] 作为列 headers 与 LoadFromCollection
How to use [Display(Name="")] as column headers with LoadFromCollection
在我的 MVC 5 站点中,我有一个稳定的导出到 Excel 功能,但用户要求我将列 headers "user friendly."
在我的模型中,我使用了 [Display(Name="Friendly Column Name")]
注释,它们按预期出现在视图页面上,但当用户触发导出时它们不会转移到导出的 Excel 文件中功能。相反,真实姓名出现了。
我知道我可以通过 LoadFromCollection 之外的其他方法加载工作表单元格,但我想知道是否仍然可以使用 LoadFromCollection[=28] =] 并使用模型的 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");
}
一种解决方法是覆盖 header 单元格,但这是不可取的,原因有二:(1) 我已经将列名写为模型中的注释,这意味着我现在拥有相同的信息写在两个不同的地方,并且 (2) 我必须手动保持信息同步,以防用户想要更多更改,而我可能会忘记这样做。
// 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";
写到这里,我真的希望这不是唯一的选择。必须有一种方法可以在 header 中写入显示名称值而不是真实名称。
LoadFromCollection 仅响应 DisplayName
或 Description
属性,而不响应 Display
属性。
所以您可以尝试将这些属性之一添加到您当前的属性中。
[DisplayName("Friendly Column Name")]
[Display(Name = "Friendly Column Name")]
public string StudentName { get; set; }
还要确保在调用 LoadFromCollection 时将 PrintHeaders 参数设置为 true,但你说出现了真实名称,所以这可能已经没问题了。
#正在将记录导出到 csv 文件。
1. 使用 headers
创建模型 class
public class EmployeeDetails
{
[Name("ID")]
public string id{ get; set; }
[Name("Name")]
public string name{ get; set; }
[Name("Designation")]
public string designation{ get; set; }
}
2.Export 使用 CSV 助手 class
var data = new EmployeeDetails();
List<EmployeeDetails> rows = new List<EmployeeDetails>() { data };
using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream))
using (var csvWriter = new CsvWriter(streamWriter, CultureInfo.CurrentCulture))
{
csvWriter.WriteHeader(typeof(EmployeeDetails));
csvWriter.NextRecord();
csvWriter.WriteRecords(rows);
csvWriter.Flush();
streamWriter.Flush();
memoryStream.Position = 0;
return memoryStream;
}
在我的 MVC 5 站点中,我有一个稳定的导出到 Excel 功能,但用户要求我将列 headers "user friendly."
在我的模型中,我使用了 [Display(Name="Friendly Column Name")]
注释,它们按预期出现在视图页面上,但当用户触发导出时它们不会转移到导出的 Excel 文件中功能。相反,真实姓名出现了。
我知道我可以通过 LoadFromCollection 之外的其他方法加载工作表单元格,但我想知道是否仍然可以使用 LoadFromCollection[=28] =] 并使用模型的 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");
}
一种解决方法是覆盖 header 单元格,但这是不可取的,原因有二:(1) 我已经将列名写为模型中的注释,这意味着我现在拥有相同的信息写在两个不同的地方,并且 (2) 我必须手动保持信息同步,以防用户想要更多更改,而我可能会忘记这样做。
// 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";
写到这里,我真的希望这不是唯一的选择。必须有一种方法可以在 header 中写入显示名称值而不是真实名称。
LoadFromCollection 仅响应 DisplayName
或 Description
属性,而不响应 Display
属性。
所以您可以尝试将这些属性之一添加到您当前的属性中。
[DisplayName("Friendly Column Name")]
[Display(Name = "Friendly Column Name")]
public string StudentName { get; set; }
还要确保在调用 LoadFromCollection 时将 PrintHeaders 参数设置为 true,但你说出现了真实名称,所以这可能已经没问题了。
#正在将记录导出到 csv 文件。
1. 使用 headers
public class EmployeeDetails
{
[Name("ID")]
public string id{ get; set; }
[Name("Name")]
public string name{ get; set; }
[Name("Designation")]
public string designation{ get; set; }
}
2.Export 使用 CSV 助手 class
var data = new EmployeeDetails();
List<EmployeeDetails> rows = new List<EmployeeDetails>() { data };
using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream))
using (var csvWriter = new CsvWriter(streamWriter, CultureInfo.CurrentCulture))
{
csvWriter.WriteHeader(typeof(EmployeeDetails));
csvWriter.NextRecord();
csvWriter.WriteRecords(rows);
csvWriter.Flush();
streamWriter.Flush();
memoryStream.Position = 0;
return memoryStream;
}