Excel date format using EPPlus

后端 未结 9 557
长情又很酷
长情又很酷 2020-12-18 17:44

I\'m having trouble with format my cells to Date.

FileInfo info = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(info))
{
      ExcelWork         


        
9条回答
  •  清歌不尽
    2020-12-18 18:13

    Generic solution which takes IEnumerable (data) it loops through the properties of the generic object finds which is of DateType or nullableDate Type and applies formatting:

       //set the list of dateColumns which will be used to formate them
                List dateColumns = new List();
    
                //get the first indexer
                int datecolumn = 1;
    
                //loop through the object and get the list of datecolumns
                foreach (var PropertyInfo in data.FirstOrDefault().GetType().GetProperties())
                {
                    //check if property is of DateTime type or nullable DateTime type
                    if (PropertyInfo.PropertyType == typeof(DateTime) || PropertyInfo.PropertyType == typeof(DateTime?))
                    {
                        dateColumns.Add(datecolumn);
                    }
                    datecolumn++;
                }
    
                // Create the file using the FileInfo object
                var file = new FileInfo(outputDir + fileName);
    
                //create new excel package and save it
                using (var package = new ExcelPackage())
                {
                    //create new worksheet
                    var worksheet = package.Workbook.Worksheets.Add("Results");
    
    
                    // add headers
                    worksheet.Cells["A1"].LoadFromCollection(data, true);
    
                    //format date field 
                    dateColumns.ForEach(item => worksheet.Column(item).Style.Numberformat.Format = "dd-mm-yyyy");
    
                    // auto size columns
                    worksheet.Cells.AutoFitColumns();
    
                    //save package
                    package.SaveAs(file);
                }
    

提交回复
热议问题