Excel Date column returning INT using EPPlus

Tsukasa picture Tsukasa · Jul 24, 2014 · Viewed 25.4k times · Source

So i'm using EPPlus to read and write excel documents.

Workflow

  • User generates populated excel document
  • Opens document and adds a row
  • Uploaded and read

The dates that are generated when I create the document using EPPlus show correctly when I'm reading the value back but the row the user changes the date one or adds is showing as an INT value not something I can use as a real date.

When I enter the date 1/01/2014 and write it, the output when I open the file up shows 41640

I'm reading it as follows

sheet.Cells[i, "AE".ConvertExcelColumnIndex()].Value != null
     ? sheet.Cells[i, "AE".ConvertExcelColumnIndex()].Value.ToString().Trim()
         : string.Empty

Update

When exporting the file I have added the following

DateTime testDate;

if (DateTime.TryParse(split[i], out testDate))
{
    sheet.Cells[row, i + 1].Style.Numberformat.Format = "MM/dd/yyyy";
    sheet.Cells[row, i + 1].Value = testDate.ToString("MM/dd/yyyy");
}

Also when reading the value back I have tried

sheet.Cells[i, "AE".ConvertExcelColumnIndex()].Style.Numberformat.Format = "MM/dd/yyy";

I still get an INT back

Answer

Tim Schmelter picture Tim Schmelter · Jul 24, 2014

...when I need to read that excel file, the only dates that are incorrect are the ones the user has changed

So when you read the modified excel-sheet, the modified dates are numbers whereas the unchanged values are strings in your date-format?

You could get the DateTime via DateTime.FromOADate:

long dateNum = long.Parse(worksheet.Cells[row, column].Value.ToString());
DateTime result = DateTime.FromOADate(dateNum);

With your sample-number:

Console.Write(DateTime.FromOADate(41640)); // ->  01/01/2014