简体   繁体   English

C#没有从电子表格中读取excel日期

[英]C# not reading excel date from spreadsheet

I uploaded an excel spreadsheet using Microsoft.Office.Interop.Excel. 我使用Microsoft.Office.Interop.Excel上传了一个excel电子表格。 When I try to read cells with a date value in order to insert it into my data set, its not being recognized as a date and it comes up as a random number? 当我尝试读取具有日期值的单元格以将其插入到我的数据集中时,它不被识别为日期并且它作为随机数出现? this is the way that I refer to the cell: 这是我引用单元格的方式:

Excel.Range startDate = objsheet.get_Range("C1:C" + lastUsedRow, System.Type.Missing);
double dbl = Convert.ToDouble(startDate);
DateTime conv = DateTime.FromOADate(dbl);
(row[3] = ((Microsoft.Office.Interop.Excel.Range)objsheet.Cells[rowIndex, 4]).Value2;)

From https://stackoverflow.com/a/4538367/1397117 来自https://stackoverflow.com/a/4538367/1397117

You need to convert the date format from OLE Automation to the .net format by using DateTime.FromOADate. 您需要使用DateTime.FromOADate将日期格式从OLE自动化转换为.net格式。

 double d = double.Parse(b); DateTime conv = DateTime.FromOADate(d); 

And I echo suggestions below that answer to use .Value instead of .Value2 . 我回应下面的建议回答使用.Value而不是.Value2

row[3] = Convert.ToDateTime(((Microsoft.Office.Interop.Excel.Range)objsheet.Cells[rowIndex, 4]).Value2.ToString());

可以为你做,看看这个林肯

In my project when I had to read data from excel, I created a method which takes cell text as input and C# DateTime as output. 在我必须从excel读取数据的项目中,我创建了一个方法,它将单元格文本作为输入,将C#DateTime作为输出。

public DateTime ReadDateFromExcel(string dateFromXL)
{
    Regex dateRegex = new Regex("^([1-9]|0[1-9]|1[0-2])[- / .]([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])[- / .](1[9][0-9][0-9]|2[0][0-9][0-9])$");
    DateTime dtParam = new DateTime();            
    if (!DateTime.TryParse(dateFromXL, out dtParam))
    {
        double oaDate = 0;
        if (Double.TryParse(dateFromXL, out oaDate))
        {
            dateFromXL = DateTime.FromOADate(oaDate).ToString("MM/dd/yyyy");
            if (!dateRegex.IsMatch(dateFromXL))
            {
                Console.Writeline("Date not in correct format");
            }
            else
            {
                dtParam = readDateFromExcel(dateFromXL);
            }
        }
        else
        {
            Console.Writeline("Date not in correct format");
        }
    }
    else
    {
        Console.Writeline("Date is in correct format");
    }
    return dtParam;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM