Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel Date Field Conversion Problem

Tags:

c#

excel

I currently have an excel sheet with one of the columns being in the date format.

What I see when I open up the spreadsheet is something like 12/29/09 and the program sees 40176.

I figured out this is the value present when I change the column to general text.

My question is how can I read the value 12/29/09 instead of 40176 or how can I change 40176 into a valid date?

My program is in c# Must be read in in c#


Here is sample code of my connection if it helps any.

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
string myPath = @"C:\Test.xls";
excelApp.Workbooks.Open(myPath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);

 Microsoft.Office.Interop.Excel.Sheets sheets = excelApp.Worksheets;
 Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
 excelApp.Visible = true;

 if(((Microsoft.Office.Interop.Excel.Range)excelApp.Cells[r, 1]).Value2 != null)
     DateString = ((Microsoft.Office.Interop.Excel.Range)excelApp.Cells[r, 1]).Value2.ToString();
like image 722
corymathews Avatar asked Dec 07 '22 07:12

corymathews


2 Answers

You can use DateTime.FromOADate() to convert the double into a DateTime value.

like image 113
Reed Copsey Avatar answered Dec 28 '22 23:12

Reed Copsey


As Reed Copsey said, the DateTime.FromOADate() method will convert the value into a DateTime. If, however, you want 12/29/09 as a string, and don't want to manipulate it any further, you can use cell.Text instead.

like image 27
Ant Avatar answered Dec 29 '22 00:12

Ant