2010-05-14 66 views
0

我正在從C#interop服務逐個單元格讀取Excel工作表。而我的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 

獲取日期格式。這是爲什麼發生?它引發「輸入字符串格式不正確」的異常。爲什麼它不會像同一列的其他單元格一樣生成雙精度值?

回答

0

也許在這些細胞中的值實際上是一個字符串

+0

是,即,但應該怎樣解決?我做對了嗎? – 2010-05-14 13:56:07

0

無論如何,我找到了解決辦法:

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