C# NPOI 读取日期格式数据不准确问题

使用NPOI读取row.GetCell(9).ToString() excel文件的带日期时间数据,结果为1/19/22 8:26:00

C#无法正确识别为datetime格式

解决方法:

 row.GetCell(10).DateCellValue.ToString();

或者网友方案:

C# NPOI读取excel日期格式的问题(2020-08-15 变成 12-5月-2020了) - 包子789654 - 博客园

string strDeliveryTime = null;
if (currentRow.GetCell(dicData["需求日期"]).CellType == CellType.Numeric)
{
strDeliveryTime = Convert.ToDateTime(currentRow.GetCell(dicData["需求日期"]).DateCellValue)
.ToString("yyyy-MM-dd");
}
else
{
strDeliveryTime = currentRow.GetCell(dicData["需求日期"]).ToString();
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这种情况可能是由于NPOI默认将数字列识别为Double类,而Double类的精度有限,可能会出现不正确的情况。你可以尝试将数字列识别为Decimal类,这样可以提高精度。具体操作可以参考以下代码: ``` using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System.Data; public static DataTable ExcelToDataTable(string filePath) { DataTable dt = new DataTable(); IWorkbook workbook; ISheet sheet; int startRow = 0; using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { workbook = new XSSFWorkbook(fs); //使用xlsx格式读取 sheet = workbook.GetSheetAt(0); if (sheet != null) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { ICell cell = firstRow.GetCell(i); if (cell != null) { dt.Columns.Add(cell.ToString()); } } startRow = sheet.FirstRowNum + 1; //读取数据 for (int i = startRow; i <= sheet.LastRowNum; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; DataRow dataRow = dt.NewRow(); bool isAllEmpty = true; for (int j = row.FirstCellNum; j < cellCount; ++j) { ICell cell = row.GetCell(j); if (cell == null) { dataRow[j] = ""; } else { if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell)) //处理日期类 { dataRow[j] = cell.DateCellValue.ToString("yyyy-MM-dd HH:mm:ss"); } else { dataRow[j] = cell.ToString(); } //将数字列识别为Decimal类 if (cell.CellType == CellType.Numeric && dt.Columns[j].DataType == typeof(decimal)) { dataRow[j] = Convert.ToDecimal(cell.NumericCellValue); } } if (!string.IsNullOrEmpty(dataRow[j].ToString().Trim())) { isAllEmpty = false; } } if (!isAllEmpty) { dt.Rows.Add(dataRow); } } } } return dt; } ``` 在读取数据时,判断列的数据是否为Decimal类,如果是,则将数字列的值转换成Decimal类。这样可以避免Double类的精度问题

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值