【问题标题】:C# not reading excel date from spreadsheetC# 不从电子表格中读取 excel 日期
【发布时间】:2013-07-29 14:54:21
【问题描述】:

我使用 Microsoft.Office.Interop.Excel 上传了一个 Excel 电子表格。当我尝试读取具有日期值的单元格以便将其插入我的数据集中时,它不会被识别为日期并且它会作为随机数出现? 这是我引用单元格的方式:

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;)

【问题讨论】:

  • 显示结果?另外:尝试使用 .Value 而不是 value2
  • 张贴您的 Excel 文件的一部分,以便我们检查您的日期格式。

标签: c# excel


【解决方案1】:

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

您需要将日期格式从 OLE 自动化转换为 .net 使用 DateTime.FromOADate 格式化。

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

我在该答案下方回应使用.Value 而不是.Value2 的建议。

【讨论】:

  • 我应该作为 b 传递什么?范围?这给出了一个错误?
  • 我似乎无法弄清楚...我收到这样的错误:无法将“System.__ComObject”类型的 COM 对象转换为接口类型“System.IConvertible”。此操作失败,因为 IID 为“{805E3B62-B5E9-393D-8941-377D8BF4556B}”的接口的 COM 组件上的 QueryInterface 调用因以下错误而失败:不支持此类接口(来自 HRESULT 的异常:0x80004002 (E_NOINTERFACE)) .
【解决方案2】:
row[3] = Convert.ToDateTime(((Microsoft.Office.Interop.Excel.Range)objsheet.Cells[rowIndex, 4]).Value2.ToString());

可以为你做,见link。

【讨论】:

    【解决方案3】:

    在我的项目中,当我不得不从 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      相关资源
      最近更新 更多