Input string was not in a correct format while reading date from excel

和自甴很熟 提交于 2020-07-10 07:25:08

问题


I am trying to upload an excel sheet. Now I am getting an error for the date column. I was able to fix it up to this point base on some suggestions here. This is the date format on the excel 20/4/2020

But I couldn't figure it out from this point. I kept getting. I was able to get the Value from the excel sheet and stored in string date

Input string was not in a correct format. at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type) at System.Double.Parse(String s)

Here is my code below

//be on the first column [r,c]
int row = 2;
for (int i = 2; i <= noOfRow; i++)   //start from the second row
{
    if (!string.IsNullOrEmpty(workSheet.Cells[i, 3].Text))
    {
        string date = workSheet.Cells[i, 3].Value.ToString();

        try
        {
            double d = double.Parse(date);//Error is coming from here
            DateTime conv = DateTime.FromOADate(d);

        }
        catch (Exception ex)
        {}
    }
}

I will appreciate if someone can help me out Thanks


回答1:


The problem occurs because value in the variable date = "11/5/2020" is not a double value. It is a DateTime value. To fix you problem you should use the next code to convert value in the date variable into DateTime value:

DateTime d = DateTime.ParseExact(date, "d/M/yyyy", CultureInfo.InvariantCulture);

Method DateTime.ParseExact allows you to set the format of the parsed date.


The above code worked for me the day you shared with me. But now I am getting this error {"String '6/3/2020 12:00:00 AM' was not recognized as a valid DateTime."} I have tried implementing almost everything on stackoverflow.

If date string in your excel file can be in different formats, then you can use overload of the method DateTime.ParseExact that supports specifying several parse formats. For example:

string[] formats = {"d/M/yyyy", "d/M/yyyy hh:mm:ss tt"};
DateTime d = DateTime.ParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);

Here is complete sample that demostrates this overload of the method DateTime.ParseExact.



来源:https://stackoverflow.com/questions/61747824/input-string-was-not-in-a-correct-format-while-reading-date-from-excel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!