Why this with Excel sheet reading?
I am reading the Excel sheet from C# interop services cell by cell. Whereas my Excel sheet has Date cells. It generates some double values, I am converting them in date by:
double dbl = Convert.ToDouble(((Excel.Range)worksheet.Cells[iRowindex,开发者_高级运维 colIndex_q17]).Value2);
string strDate3 = DateTime.FromOADate(dbl).ToShortDateString();
drRow[dtSourceEXLData.Columns[constants.VisualDate]] = strDate3;
OK? But some time happening the value of
((Excel.Range)worksheet.Cells[iRowindex,colIndex_q17]).Value2
getting date format. Why is this happening? It throws an exception of "input string not in correct format". Why is it not generating a double value like other cells of same column?
Perhaps the value in those cells is actually a string
Anyway, I found the solution:
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();
精彩评论