由于您在字符串 ( 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();
}
}
这给出了这个:
