Excel date format using EPPlus

人盡茶涼 提交于 2019-11-28 02:23:32

问题


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

FileInfo info = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(info))
{
      ExcelWorksheet ws = package.Workbook.Worksheets.Add(sheetName);
      ws.Cells[3, 1].Style.Numberformat.Format = "yyyy-mm-dd";
      ws.Cells["A3"].Formula = "=DATE(2014,10,5)";
}

Output from this in Excel: 41 917,00

Why is this not working?


回答1:


I agree with Yosoyke. You're probably targeting the wrong cells. You can try:

ws.Cells["A3"].Style.Numberformat.Format = "yyyy-mm-dd";
ws.Cells["A3"].Formula = "=DATE(2014,10,5)";



回答2:


worksheet.Cells["YOURDATECELL_OR_YOURDATECELLRANGE"].Style.Numberformat.Format = "mm-dd-yy";

if you use the formula mentioned by taraz. do add worksheet.Calculate() in the end. reference https://epplus.codeplex.com/wikipage?title=About%20Formula%20calculation

Or instead of using formula, Alternative approach

private static decimal GetExcelDecimalValueForDate(DateTime date)
{
    DateTime start = new DateTime(1900, 1, 1);
    TimeSpan diff = date - start;
    return diff.Days + 2;
}

Reference

worksheet.Cells["A2"].Value = GetExcelDecimalValueForDate(Convert.ToDateTime('2016-04-29'));
worksheet.Cells["A2"].Style.Numberformat.Format = "mm-dd-yy";//or m/d/yy h:mm

By Default when excel saves a date field it saves it as numFormatId 14(Look at the xml files in the xls). This ensure the date formats correctly in any country when the file is opened. In Epplus mm-dd-yy translates to numFormatId 14 for excel. This will ensure that when the file is opened in any country the date will be formatted correctly based on the country's short date settings. Also noticed m/d/yy h:mm formats correctly for any country.




回答3:


var dateColumns = from DataColumn d in dt.Columns
                  where d.DataType == typeof(DateTime) || d.ColumnName.Contains("Date")
                  select d.Ordinal + 1;

foreach (var dc in dateColumns)
{
    worksheet.Cells[2, dc, rowCount + 2, dc].Style.Numberformat.Format = "mm/dd/yyyy hh:mm:ss AM/PM";
}

it will format all the columns with header Date to specific format given/ provided




回答4:


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<int> dateColumns = new List<int>();

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



回答5:


Some news:

ws.Cells["A3"].Style.Numberformat.Format = "[$-en-US]yyyy-mmm-dd";
ws.Cells["A3"].Formula = "=DATE(2014,10,5)";




回答6:


I was having the same problem with my CSV to be transformed. I was able to do this in a little different manner.

private string ConvertToExcel(string CSVpath, string EXCELPath)
    {
        try
        {
            string Filename = System.IO.Path.GetFileNameWithoutExtension(CSVpath);
            string DirectoryName = System.IO.Path.GetDirectoryName(CSVpath);
            EXCELPath = DirectoryName + "\\" + Filename + ".xlsx";

            string worksheetsName = "Report";
            bool firstRowIsHeader = false;

            var format = new OfficeOpenXml.ExcelTextFormat();
            format.Delimiter = '|';
            format.EOL = "\n";

            using (OfficeOpenXml.ExcelPackage package = new OfficeOpenXml.ExcelPackage(new System.IO.FileInfo(EXCELPath)))
            {
                string dateformat = "m/d/yy h:mm";
                //string dateformat = System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern;

                OfficeOpenXml.ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);
                worksheet.Cells["A1"].LoadFromText(new System.IO.FileInfo(CSVpath), format, OfficeOpenXml.Table.TableStyles.Medium2, firstRowIsHeader);

                worksheet.Column(3).Style.Numberformat.Format = dateformat;
                worksheet.Column(5).Style.Numberformat.Format = dateformat;
                worksheet.Column(6).Style.Numberformat.Format = dateformat;
                worksheet.Column(20).Style.Numberformat.Format = dateformat;
                worksheet.Column(21).Style.Numberformat.Format = dateformat;
                worksheet.Column(22).Style.Numberformat.Format = dateformat;




                package.Save();
            }
        }
        catch (Exception ex)
        {
            //DAL.Operations.Logger.LogError(ex);
            Console.WriteLine(ex);
            Console.Read();
        }
        return EXCELPath;
    }


来源:https://stackoverflow.com/questions/22832423/excel-date-format-using-epplus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!