在C#中使用EPPLUS设置列数据格式

问题

当我使用EPPLUS库导出Microsoft Excel spreadsheet ,我需要设置列的数据格式以及单元格格式,以便可以通过Microsoft Excel's formulas处理date和时间来识别Microsoft Excel电子表格中的结果date。

什么尝试

我可以很容易地设置单元格的格式:

 currentWorkSheet.Cells["L" + currentRowNumber.ToString()].Style.Numberformat.Format = "m/d/yyyy"; currentWorkSheet.Cells["L" + currentRowNumber.ToString()].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Right; 

问题是,即使使用此数字格式和样式单元格中的date仍不被识别为date,它只是格式化为date。

经过研究,我发现我需要设置该列有一个“date”数据,如图所示: 图片

我试图设置列的数据types,但是这不起作用:

 currentWorkSheet.Column(10).Style.Numberformat.Format = "Date"; 

我能做些什么来获得列的数据types是一个date?

我试了一下,发现如果我的系统中设置的date格式完全正确,那么Excel会将其作为date值types,否则将其视为用户定义。 我的系统date格式是“dd.MM.yyyy”,并且由于这个代码在Excel文件中的单元格“A3”具有date格式,单元格“A2”有用户定义。 你可以检查一下。

我的testing用例是:

 using (ExcelPackage testFile = new ExcelPackage(new System.IO.FileInfo(@"c:\Data\test.xlsx"))) { ExcelWorksheet testSht = testFile.Workbook.Worksheets[1]; testSht.Cells[1, 1].Value = new DateTime(2017, 1, 1); testSht.Cells[2, 1].Style.Numberformat.Format = "dd-mm-yyyy"; testSht.Cells[2, 1].Formula = "=Date(" + DateTime.Now.Year + "," + DateTime.Now.Month + "," + DateTime.Now.Day + ")"; testSht.Cells[3, 1].Value = new DateTime(2017, 1, 1); testSht.Cells[3, 1].Style.Numberformat.Format = "dd.MM.yyyy"; testFile.Save(); }