EPPLus Excel将日期与日期时间列中的月份进行交换

问题描述 投票:0回答:1

我有网站,用户可以在其中下载通过EPPLus扩展名生成的excel。

using (ExcelPackage pck = new ExcelPackage())
{
      ExcelWorksheet ws = pck.Workbook.Worksheets.Add("dates");

      // Create table from dataTable with header
      ws.Cells["A1"].LoadFromCollection(dates, true, TableStyles.Medium6);

      string dateformat = System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
      ws.Column(2).Style.Numberformat.Format = dateformat;

      // Autofit Columns               
      ws.Cells[ws.Dimension.Address].AutoFitColumns();

      // Send to browser
      fileBytes = pck.GetAsByteArray();
}
return File(fileBytes, "application/vnd.ms-excel", "dates.xlsx");

下载正常。下载的excel有两列,第二列是日期时间,我将其格式化为ShortDate

string dateformat = System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
ws.Column(2).Style.Numberformat.Format = dateformat;

当我打开excel时,对于美国地区来说,它工作正常(日期时间值与地区设置中的短日期匹配)

enter image description hereenter image description here

但是当我将地区更改为捷克语时

enter image description hereenter image description here

Excel中的日期与短日期的区域设置不匹配,因为日期和月份已互换。为什么会这样,我该如何解决呢?我想念什么?

c# windows excel-2007 epplus
1个回答
0
投票

在您的控制器中,您可以从请求对象中捕获当前用户的语言设置,如下所示:

string language= Request.UserLanguages.FirstOrDefault() ?? "en-US";

[如果出于某种原因,集合为空,则设置后备语言,这里是美国英语。然后,将此字符串传递给Excel函数,在该函数中要做的第一件事就是用用户语言创建一个新的CultureInfo对象,并在当前线程中对其进行更改:

CultureInfo currentCulture = new CultureInfo(language, false);
Thread.CurrentThread.CurrentCulture = currentCulture;

您现在可以通过使用DateTimeFormatInfo.CurrentInfo类型以正确的格式设置所选单元格的样式:

// Load collection into excel AND FORMAT THE CELLS
workSheet.Cells["A1"].LoadFromCollection(dates, true, TableStyles.Medium6).Style.Numberformat.Format = DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
© www.soinside.com 2019 - 2024. All rights reserved.