krobelusmeetsyndra
krobelusmeetsyndra

Reputation: 181

Date is converted to double when fetched from Worksheet

I have an application that manipulates data from an Excel workbook. In a given cell, I have a date in the format "dd/mm/yyyy", which I need to display on screen. I use the following code to get it from the worksheet:

dateLabel.Text = excelApp.WorksheetFunction.VLookup(input, sheetToLook.Range["A2:G4"], 3, false).ToString();

Where excelApp is defined as Microsoft.Office.Interop.Excel.Application excelApp, and input is a string to locate the correct row.

However, when I run the application, I get the following value:

Start Date: 43325

Expected result is 13/08/2018. What am I missing on? Any help will be greatly appreciated!

Upvotes: 0

Views: 700

Answers (1)

Kevin Mills
Kevin Mills

Reputation: 407

You will need to use DateTime.FromOADate() to convert from an OADate (OLE Automation Date) to a standard C# DateTime. In your particular example, DateTime.FromOADate(excelApp.WorksheetFunction.VLookup(input, sheetToLook.Range["A2:G4"], 3, false)). You will probably want to add some data checking for the data that you pull in from that field, as DateTime.FromOADate() requires a double as the input. I would probably code it as below

var excelDate = excelApp.WorksheetFunction.VLookup(input, sheetToLook.Range["A2:G4"], 3, false);

if(excelDate is double oaDate)
{
    dateLabel.Text = DateTime.FromOADate(oaDate);
}

Upvotes: 1

Related Questions