我想使用epplus将excel中的一列读入数据表,但是每当我这样做时,我都会获得24小时格式的时间。我希望时间采用Excel中的12小时制。
我尝试将excel的日期格式更改为“ dd / mm / yyyy hh:mm:ss tt”,它为我提供AM / PM,但它以24小时格式显示时间。
worksheet.Cells["" + firstRowCell.Address + ":" +
Regex.Replace(firstRowCell.Address, "[0-9]", "") + "" +
worksheet.Dimension.Rows].Style.Numberformat.Format = "dd/mm/yyyy hh:mm:ss tt";
答案 0 :(得分:1)
It sounds like you are reading formatted display value and not the underlying cell value. Maybe this will help you I am not sure Excel saves the date and time as a double of the number of days from 1900-01-01 the decimal part is how it determines hours in the day. This number could also be negative or positive so what I have done in the past to get the correct value is to read the cell value and convert that to a DateTime.
//get the underlying value instead of the display value
var cellValue = worksheet.Cells["" + firstRowCell.Address + ":" +
Regex.Replace(firstRowCell.Address, "[0-9]", "") + "" +
worksheet.Dimension.Rows].Value;
var stringValue = $"{cellValue}";
//Now convert the double to a valid DateTime;
DateTime value;
var date = new DateTime(1899, 12, 30);
double doubleValue;
if (double.TryParse(stringValue, out doubleValue) &&
(doubleValue <= 2958465) &&
(doubleValue >= -693593))
value = date.AddDays(doubleValue);
Once you have a valid DateTime value you can use ToString to get a proper 12 hour format
value.ToString("dd/mm/yyyy hh:mm:ss tt")