簡體   English   中英

如何使用 [Display(Name="")] 作為 LoadFromCollection 的列標題

[英]How to use [Display(Name="")] as column headers with LoadFromCollection

在我的 MVC 5 站點中,我有一個穩定的導出到 Excel 功能,但用戶要求我將列標題設置為“用戶友好”。

在我的模型中,我使用了[Display(Name="Friendly Column Name")]注釋,它們在視圖頁面上按預期顯示,但當用戶觸發導出功能時,它們不會轉移到導出的 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)我已經在模型中將列名寫為注釋,這意味着我現在在兩個不同的地方寫了相同的信息,以及(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";                               

既然如此,我真的希望這不是唯一的選擇。 必須有一種方法可以在標題中寫入顯示名稱值而不是真實名稱。

LoadFromCollection僅響應DisplayNameDescription屬性,而不響應Display屬性。

因此,您可以嘗試將這些屬性之一添加到您當前的屬性中。

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

還要確保在調用LoadFromCollection時將 PrintHeaders 參數設置為 true ,但您說的是真實姓名,所以這可能已經沒問題了。

#導出記錄到csv文件。
1. 創建一個帶有標題的模型類

               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.使用 CSV Helper 類導出

       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;
                   }  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM