首页 > 解决方案 > 从 excel 读取日期时输入字符串的格式不正确

问题描述

我正在尝试上传 Excel 表格。现在我收到日期列的错误。根据此处的一些建议,我能够将其修复到这一点。这是 excel 上的日期格式 20/4/2020

但我无法从这一点上弄清楚。我不断得到。我能够从 excel 表中获取值并存储在字符串日期中

输入字符串的格式不正确。在 System.Number.ThrowOverflowOrFormatException(ParsingStatus 状态,TypeCode 类型) 在 System.Double.Parse(String s)

这是我下面的代码

//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)
        {}
    }
}

如果有人可以帮助我,我将不胜感激谢谢

标签: c#exceldate

解决方案


出现问题是因为变量中的值date = "11/5/2020"不是double值。这是一个DateTime值。要解决您的问题,您应该使用下一个代码将date变量中的值转换为DateTime值:

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

方法DateTime.ParseExact允许您设置解析日期的格式。


上面的代码在你与我分享的那一天对我有用。但是现在我遇到了这个错误{"String '6/3/2020 12:00:00 AM' was not recognized as a valid DateTime."},我尝试在 stackoverflow 上实现几乎所有内容。

如果您的excel文件中的日期字符串可以是不同的格式,那么您可以使用DateTime.ParseExact支持指定几种解析格式的方法的重载。例如:

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

这是演示该方法重载的完整示例DateTime.ParseExact


推荐阅读