在epplus中转换DateTime格式
Convert DateTime format in epplus
我想使用 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";
听起来您正在读取格式化的显示值而不是基础单元格值。也许这会对您有所帮助我不确定 Excel 将日期和时间保存为从 1900-01-01 开始的天数的两倍小数部分是它如何确定一天中的小时数。这个数字也可以是负数或正数,所以我过去为获得正确的值所做的是读取单元格值并将其转换为 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);
获得有效的 DateTime 值后,您可以使用 ToString 获得正确的 12 小时格式
value.ToString("dd/mm/yyyy hh:mm:ss tt")
我想使用 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";
听起来您正在读取格式化的显示值而不是基础单元格值。也许这会对您有所帮助我不确定 Excel 将日期和时间保存为从 1900-01-01 开始的天数的两倍小数部分是它如何确定一天中的小时数。这个数字也可以是负数或正数,所以我过去为获得正确的值所做的是读取单元格值并将其转换为 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);
获得有效的 DateTime 值后,您可以使用 ToString 获得正确的 12 小时格式
value.ToString("dd/mm/yyyy hh:mm:ss tt")