使用EPPlus的Excel日期格式

时间:2014-04-03 08:49:52

标签: c# epplus

我将格式化格式化为日期时遇到了问题。

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

在Excel中输出:41 917,00

为什么这不起作用?

10 个答案:

答案 0 :(得分:59)

我同意Yosoyke。你可能是针对错误的细胞。你可以尝试:

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

答案 1 :(得分:10)

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

如果你使用taraz提到的公式。最后添加workheet.Calculate()。 参考 https://epplus.codeplex.com/wikipage?title=About%20Formula%20calculation

或者不使用公式,替代方法

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

默认情况下,当Excel保存日期字段时,它会将其保存为numFormatId 14(查看xls中的xml文件)。这样可确保在打开文件时在任何国家/地区正确格式化日期。 在Epplus中mm-dd-yy转换为numFormatId 14 for excel。 这将确保在任何国家/地区打开文件时,将根据国家/地区的短日期设置正确格式化日期。 还注意到m/d/yy h:mm格式正确适用于任何国家/地区。

答案 2 :(得分:4)

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

它会将标题为Date的所有列格式化为给定/提供的特定格式

答案 3 :(得分:1)

如果您想使用AM / PM,可以尝试

   worksheet.Cells[1].Style.Numberformat.Format = "dd/MM/yyyy  HH:mm:ss AM/PM";

答案 4 :(得分:0)

一些新闻:

  

ws.Cells [“A3”]。Style.Numberformat.Format =“[$ -en-US] yyyy-mmm-dd”;

  ws.Cells [“A3”]。公式=“= DATE(2014,10,5)”;

答案 5 :(得分:0)

采用IEnumerable(数据)的通用解决方案,它循环遍历通用对象的属性,找到具有DateType或nullableDate Type的对象并应用格式:

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

答案 6 :(得分:0)

我要转换的CSV遇到相同的问题。我能够以一些不同的方式做到这一点。

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

答案 7 :(得分:0)

在非常好的Generic solution which takes IEnumerable..答案之后,我们不得不更进一步,为不同的属性显示不同的日期格式。例如,某些列需要显示为dd/MM/yyyy,而另一些列需要显示为dd/MM/yyyy hh:mm

因此,我们在属性中添加了DisplayFormatDataFormatStringrepresenting a DateTime format)注解,如下所示:

using System.ComponentModel.DataAnnotations;
...
[DisplayName("Download Date")]
[DisplayFormat(DataFormatString = "dd/MM/yyyy hh:mm")]
public string DownloadDate { get; set; }
...

然后在迭代数据对象的属性时从Generic solution which takes IEnumerable..借用DisplayFormat注释中提取日期格式字符串:

public void FormatDateColumns(ExcelWorksheet worksheet, IEnumerable<IResult> data)
{
    // Dictionary 'key' contains the Index of the column that contains DateTime data
    // Dictionary 'value' contains the DateTime format for that column
    Dictionary<int, string> dateColumns = new Dictionary<int, string>();
    int dateColumnIndex = 1;

    // find all the DateTime/DateTime? columns in the data object 
    foreach (var PropertyInfo in data.FirstOrDefault().GetType().GetProperties())
    {
        if (PropertyInfo.PropertyType == typeof(DateTime) || PropertyInfo.PropertyType == typeof(DateTime?))
        {
            string dateTimeFormat = Constants.DefaultDateTimeFormat;

            // attempt to get a DataFormatString from a DisplayFormat annotation which may be decorating the Property
            // looking for an annotation something like [DisplayFormat(DataFormatString = "dd-MM-yyyy hh:mm")] 
            if (PropertyInfo.CustomAttributes != null)
            {
                var dislayFormatAttribute = PropertyInfo.CustomAttributes.Where(x => x.AttributeType.Name == "DisplayFormatAttribute").FirstOrDefault();
                if (dislayFormatAttribute != null && dislayFormatAttribute.NamedArguments != null && dislayFormatAttribute.NamedArguments.Count > 0)
                {
                    var displayFormatArg = dislayFormatAttribute.NamedArguments.First();
                    if (displayFormatArg != null && displayFormatArg.TypedValue != null && displayFormatArg.TypedValue.Value != null)
                    {
                        // NOTE: there is probably an easier way to get at this value?
                        dateTimeFormat = displayFormatArg.TypedValue.Value.ToString();
                    }
                }
            }

            dateColumns.Add(dateColumnIndex, dateTimeFormat);
        }
        dateColumnIndex++;
    }

    if (dateColumns.Count > 0)
    {
        // apply the formatting
        dateColumns.ToList().ForEach(item => worksheet.Column(item.Key).Style.Numberformat.Format = item.Value);
    }
}

答案 8 :(得分:0)

我想补充一下,格式设置是我的解决方案。但是,在将value属性设置为DateTime对象而不是字符串之前,我无法使其工作。那是使其全部正常工作的关键。

答案 9 :(得分:0)

我遇到了类似的问题,即使我正确设置了日期并将正确的数字格式应用于包含日期的单元格,我还是看到了日期的数字表示。

事实证明,在那之后,我应用了一种样式,有效地重置了我的格式。

代码类似于:

ws.Cells["A3"].Style.Numberformat.Format = 
System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
ws.Cells["A3"].Value = New DateTime(2021, 10, 15, 23, 16, 0).ToOADate();

后来,我有:

ws.Cells("A3").StyleName = colStyle //colstyle is a style created earlier

为了解决这个问题,我需要在设置样式后应用 NumberFormat.Format