【问题标题】:Why this with Excel sheet reading?为什么这与 Excel 工作表阅读?
【发布时间】:2010-05-14 10:39:47
【问题描述】:

我正在逐个单元格地读取 C# 互操作服务中的 Excel 工作表。而我的 Excel 工作表有日期单元格。它会生成一些双精度值,我将它们转换为日期:

 double dbl = Convert.ToDouble(((Excel.Range)worksheet.Cells[iRowindex,                colIndex_q17]).Value2);
                        string strDate3 = DateTime.FromOADate(dbl).ToShortDateString();
                        drRow[dtSourceEXLData.Columns[constants.VisualDate]] = strDate3;

好吗?但有些时候发生的价值

((Excel.Range)worksheet.Cells[iRowindex,colIndex_q17]).Value2

获取日期格式。为什么会这样?它会引发“输入字符串格式不正确”的异常。为什么它不像同一列的其他单元格那样生成双精度值?

【问题讨论】:

    标签: excel


    【解决方案1】:

    也许这些单元格中的值实际上是一个字符串

    【讨论】:

    • 是的,但解决方案应该是什么?我做对了吗?
    【解决方案2】:

    无论如何,我找到了解决方案:

    object obj=((Excel.Range)worksheet.Cells[iRowindex, colIndex_q17]).Value2;
    Type type = obj.GetType();
    string strDate3 = string.Empty;
    double dbl = 0.0;
    
    if (type == typeof(System.Double))
    {
        dbl = Convert.ToDouble(((Excel.Range)worksheet.Cells[iRowindex, colIndex_q17]).Value2);
        strDate3 = DateTime.FromOADate(dbl).ToShortDateString();
    }
    else
    {
        DateTime dt = new DateTime().Date;
        dt = Convert.ToDateTime(obj).Date;
        strDate3 = dt.ToShortDateString(); //DateTime.FromOADate(dbl).ToShortDateString();
    }
    drRow[dtSourceEXLData.Columns[constants.VisualDate]] = strDate3; //((Excel.Range)worksheet.Cells[iRowindex, colIndex_q16]).Value2.ToString();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多