How to set Column Type when using EPPlus

前端 未结 5 995
予麋鹿
予麋鹿 2021-02-02 05:12

I\'m using EPPlus to generate Excel files, in DAL I\'m populating DataTable, filling data into table, and passing table to Presentation La

5条回答
  •  野的像风
    2021-02-02 05:41

    Here's a nice C# extension method to help load from collection with headers and the proper date formatting:

    (Decorate your properties with Description attributes for the column headings)

    public static class EpPlusExtensions
    {
        public static void Load(this ExcelWorksheet worksheet, IEnumerable collection)
        {
            worksheet.Cells["A1"].LoadFromCollection(collection, true);
    
            var properties = typeof(T).GetProperties();
    
            for (var i = 0; i < properties.Length; i++)
            {
                if (new []{typeof(DateTime), typeof(DateTime?)}.Contains(properties[i].PropertyType)) 
                {
                    worksheet.Column(i + 1).Style.Numberformat.Format = "m/d/yyyy";
                }
            }
        } 
    }
    

提交回复
热议问题