首页 > 解决方案 > 有什么方法可以像在 C# 中一样使用不变的文化来格式化 Excel 中的日期单元格

问题描述

我面临的问题是在 Excel 工作表的单元格中写入了日期。单元格使用自定义格式格式化,例如:

[$-de]dd/mm/yyyy (dddd)

但只有 (dddd) 部分被处理为给我“Sonntag”(德语中的星期日)。

即使我将自定义格式的文化写为“de”,日期时间格式也不是固定的。有没有办法在不改变日期时间格式(yyyy-mm-dd)的情况下实现以下结果?

Tried                       Output                   Expected output
--------                  -----------------------   -------------------
[$-fr]yyyy-mm-dd (dddd) => 2019-07-31 (dimanche)    31/7/2019 (dimanche)  
[$-de]yyyy-mm-dd (dddd) => 2019-07-31 (Sonntag)     31.7.2019 (Sonntag)
[$-en]yyyy-mm-dd (dddd) => 2019-07-31 (Sunday)      7.31.2019 (Sunday)

标签: c#excelexcel-formulaeppluscell-formatting

解决方案


由于您在字符串 ( yyyy-mm-dd) 中指定了确切的数据格式,因此 Excel 在打开时必须遵守它。AFAIK,excel没有真正的“默认”格式与您正在寻找的内容相匹配。如果您打开 Excel 并指定单元格的格式,您可以设置文化/国家,但您仍然必须选择格式 - 第一个通常使用 / 作为分隔符。

但是,如果您想使用 .NET 中的内容,您可以使用CultureInfo.DateTimeFormat来获得我认为您所追求的内容:

CultureInfo c;
var dt = new DateTime(2019,7,31);

c = new CultureInfo("fr-FR");
Console.WriteLine($"{c}: {c.DateTimeFormat.ShortDatePattern}");
Console.WriteLine(dt.ToString($"{c.DateTimeFormat.ShortDatePattern} (dddd)", c.DateTimeFormat));
Console.WriteLine();

c = new CultureInfo("de-DE");
Console.WriteLine($"{c}: {c.DateTimeFormat.ShortDatePattern}");
Console.WriteLine(dt.ToString($"{c.DateTimeFormat.ShortDatePattern} (dddd)", c.DateTimeFormat));
Console.WriteLine();

c = new CultureInfo("en-EN");
Console.WriteLine($"{c}: {c.DateTimeFormat.ShortDatePattern}");
Console.WriteLine(dt.ToString($"{c.DateTimeFormat.ShortDatePattern} (dddd)", c.DateTimeFormat));
Console.WriteLine();

将在输出中为您提供:

fr-FR: dd/MM/yyyy
31/07/2019 (mercredi)

de-DE: dd.MM.yyyy
31.07.2019 (Mittwoch)

en-EN: M/d/yyyy
7/31/2019 (Wednesday)

要在 excel 中使用,请执行以下操作:

[TestMethod]
public void Culture_Info_Data_Format_Test()
{
    //https://stackoverflow.com/questions/56985491/is-there-any-way-to-format-date-cell-in-excel-with-invariant-culture-like-in-c-s
    var fileInfo = new FileInfo(@"c:\temp\Culture_Info_Data_Format_Test.xlsx");
    if (fileInfo.Exists)
        fileInfo.Delete();

    using (var pck = new ExcelPackage(fileInfo))
    {
        var dt = new DateTime(2019, 7, 31);
        var workbook = pck.Workbook;
        var worksheet = workbook.Worksheets.Add("Sheet1");
        worksheet.Column(1).Width = 50;

        var c = new CultureInfo("fr-FR");
        var format = $"[$-fr]{c.DateTimeFormat.ShortDatePattern} (dddd)";
        worksheet.Cells[1, 1].Value = dt;
        worksheet.Cells[1, 1].Style.Numberformat.Format = format;

        c = new CultureInfo("de-DE");
        format = $"[$-de]{c.DateTimeFormat.ShortDatePattern} (dddd)";
        worksheet.Cells[2, 1].Value = dt;
        worksheet.Cells[2, 1].Style.Numberformat.Format = format;

        c = new CultureInfo("en-EN");
        format = $"[$-en]{c.DateTimeFormat.ShortDatePattern} (dddd)";
        worksheet.Cells[3, 1].Value = dt;
        worksheet.Cells[3, 1].Style.Numberformat.Format = format;

        pck.Save();

    }

}

这给出了这个:

在此处输入图像描述


推荐阅读