当我从excel获取值时,日期更改为数字

时间:2016-02-26 11:10:18

标签: c# excel datetime dataset

我有一个包含很多字段的excel文件。我使用数据集来存储从这个excel文件中获取的数据。在Excel工作表中,我有一个日期列,设置为正确的格式。但是在检索时,格式将更改为数据集中的数字..

我不知道这个问题的原因。

Excel值:2015年12月1日,在数据集中更改为42016。

对此问题的任何指示都将不胜感激。

我的代码是

  private static DataSet GetExcelDataAsDataSet(string path)
        {

            return GetExcelDataReader(path).AsDataSet();
        }

        private static IExcelDataReader GetExcelDataReader(string path)
        {
            FileStream stream = System.IO.File.Open(path, FileMode.Open, FileAccess.Read);


            IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

            var data = excelReader.ResultsCount;
            DataSet result = excelReader.AsDataSet();


            excelReader.IsFirstRowAsColumnNames = true;

            return excelReader;
        }

1 个答案:

答案 0 :(得分:1)

this answer中所述,它就像使用一样简单:

public static DateTime FromExcelSerialDate(int SerialDate)
{
    if (SerialDate > 59) SerialDate -= 1; //Excel/Lotus 2/29/1900 bug   
    return new DateTime(1899, 12, 31).AddDays(SerialDate);
}

您获得的数字是自19/1年1月1日以来经过的天数,因此该功能就是您的答案:)

您也可以使用DateTime dt = DateTime.FromOADate(NUMBER);,我认为从this answer中提取它会更好。