Home > Enterprise >  C# DateTime from Excel turns into float number
C# DateTime from Excel turns into float number

Time:12-28

I have an excel file in the first column which contains dates in the format dd.MM.yyyy hh:mm:ss. I'm trying to display data from an excel table in datagridview, but the date is displayed as a float number.

I tried to convert the date to the desired format in this way, but it does not work: worksheet.Cells[2, 1, endCell.Row, 1].Style.Numberformat.Format = "dd.MM.yyyy hh:mm:ss";

The full code of my method:

public static DataTable readTableFromExcel(FileInfo file)
        {
            DataTable table = new DataTable();

            Console.WriteLine(file.Exists);

            using (ExcelPackage package= new ExcelPackage(file))
            {
                ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                ExcelWorksheet worksheet = package.Workbook.Worksheets[0];

                ExcelCellAddress startCell = worksheet.Dimension.Start;
                ExcelCellAddress endCell = worksheet.Dimension.End;

                ExcelRange range = worksheet.Cells[startCell.Row, startCell.Column, endCell.Row, endCell.Column];
                ExcelTable excelTable = worksheet.Tables.Add(range, "table");

                Console.WriteLine(worksheet.Cells[2, 1].Value.ToString());

                table = excelTable.ToDataTable();
            }
            
            return table;
        }

String with Console.Writeline outputs 44912,0912268519 instead of 17.12.2022 2:11:22.

Then I output the data to datagridview: tableView.DataSource = table;

And it looks like: https://i.stack.imgur.com/aXx6V.png

File used: https://drive.google.com/drive/folders/1hXKmKs_F7EyO5GdVU3HVATxDLlFWO4jk?usp=share_link

How can I display the datetime correctly?

CodePudding user response:

In Excel, dates and times are stored as a floating point number representing the number of days since the epoch date of January 1, 1970. This means that when you read a date or time value from an Excel file into a C# DateTime object, you will need to convert the floating point value to a DateTime object.

// Assume that the Excel date value is stored in a variable called "excelDate"

// Convert the Excel date value to a DateTime object
DateTime dateTime = DateTime.FromOADate(excelDate);

system.datetime.fromoadate

  • Related