简体   繁体   中英

Excel time format using Epplus

I have an excel document which I try to import to my system. (.net core 2.2 and EPPlus v4.5.3.1)

The excel data like 09:57:32 and Custom Cell format [hh]:mm:ss

private TimeSpan? GetRequiredTimeFromRowOrNull(ExcelWorksheet worksheet, int row, int column, string columnName, StringBuilder exceptionMessage)
    {
        worksheet.Cells[row, column].Style.Numberformat.Format = "hh:mm:ss";
        var cellValue = TimeSpan.Parse(worksheet.Cells[row, column].Value.ToString());

        if (cellValue.ToString() != null && !string.IsNullOrWhiteSpace(cellValue.ToString()))
        {
            return cellValue;
        }

        exceptionMessage.Append(GetLocalizedExceptionMessagePart(columnName));
        return null;
    }

"worksheet.Cells[row, column].Value" comes 0.414953703703704

and also

"worksheet.Cells[row, column].Text" comes 09:12:32

How can I get exact value?

Excel stores dates and time in decimal values. The whole-number part is the day and the decimal part is the time.

So, to get into a C# DateTime , use the OLE Automation converter:

try
{
    var val = (double)worksheet.Cells[row, column].Value;
    var dt = DateTime.FromOADate(val);
    var cellValue = dt.TimeOfDay;
}
catch (Exception)
{
    //log conversion error
}

Will want to put a Try.Catch around the cast JIC the cell does not have a number in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM