c# - 在epplus中转换日期时间格式
问题描述
我想使用 epplus 将 excel 中的一列读入数据表,但每当我这样做时,我都会以 24 小时格式获得时间。我希望时间是 12 小时格式,因为它在 excel 中。
我尝试将 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")
推荐阅读
- mysql - 为什么 MySQL 在其内部表示中打包日期类型
- ios - iOS 部署目标设置为 7.0,但此平台支持的部署目标版本范围为 8.0 到 12.1。(在目标“反应”中)
- java - 我想在 java 中读取和修改一个 .xlsm 文件,我正在使用 Apache POI。在写入 .xlsm 文件时,我的代码正在创建 0 kb 文件
- javascript - 获取在 Chrome 扩展中执行脚本的选项卡的选项卡 ID
- spring - 如何使用 Spring 将依赖项注入 javax.faces.context.ExceptionHandler?
- c# - 如何在每行从 0-100 获得 3 个数字?
- spring - springframework 网站变了 - http://www.springframework.org/beans/ 不见了?
- nginx - Docker登录未将基本身份验证标头传递给nginx
- r - 映射一个带有 CSV 保存的函数
- elasticsearch - Elasticseach - RestHighLevelClient 连接到弹性云