前言:
使用NPOI读取EXCEL日期格式数据时,返回值可能是错误的。NPOI将日期识别为数值,还需要进行额外的处理,才能保证日期读取正确。如是。
引用:
using System.IO;
using System.Data;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
读取工作表数据到DataTable代码示例:
string fileName = "Excel文件路径";
string sheetName = "Excel工作表名";
using (FileStream fs = File.OpenRead(fileName))
{
IWorkbook book = null;
if (fileName.ToLower().EndsWith("xls"))
book = new HSSFWorkbook(fs);
if (fileName.ToLower().EndsWith("xlsx"))
book = new XSSFWorkbook(fs);
var sheet = book.GetSheet(sheetName);
if (sheet == null)
throw new Exception($"Can't find sheet name of {sheetName}");
DataTable dt = new DataTable();
var firstRow = sheet.GetRow(0);
if (firstRow != null)
{
for (int columnIndex = 0; columnIndex < firstRow.LastCellNum; columnIndex++)
{
var cell = firstRow.GetCell(columnIndex);
dt.Columns.Add(cell.StringCellValue.Trim(), typeof(string));
}
for (int rowIndex = 1; rowIndex < sheet.PhysicalNumberOfRows; rowIndex++)
{
var row = sheet.GetRow(rowIndex);
if (row != null)
{
DataRow drNew = dt.NewRow();
for (int columnIndex = 0; columnIndex < firstRow.LastCellNum; columnIndex++)
{
ICell cell = row.GetCell(columnIndex);
if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell))
{
if (cell.DateCellValue.Hour > 0 || cell.DateCellValue.Minute > 0 || cell.DateCellValue.Second > 0 || cell.DateCellValue.Millisecond > 0)
{
drNew[columnIndex] = cell.DateCellValue.ToString();
}
else
{
drNew[columnIndex] = cell.DateCellValue.ToString("yyyy-MM-dd");
}
}
else
{
drNew[columnIndex] = cell.ToString();
}
}
dt.Rows.Add(drNew);
}
}
}
return dt;
其中,对日期数据的特殊识别和处理:判断数值是否为日期,并区分是否带有时间。
if (cell.CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(cell))
{
if (cell.DateCellValue.Hour > 0 || cell.DateCellValue.Minute > 0 || cell.DateCellValue.Second > 0 || cell.DateCellValue.Millisecond > 0)
{
drNew[columnIndex] = cell.DateCellValue.ToString();
}
else
{
drNew[columnIndex] = cell.DateCellValue.ToString("yyyy-MM-dd");
}
}
以上
Hope is a good thing, maybe the best of things, and no good thing ever dies. ——《The Shawshank Redemption》

本文介绍如何使用NPOI库在读取Excel时,识别并正确处理包含日期的数值格式,包括区分日期时间并转换为标准格式。通过示例代码演示了关键的日期处理逻辑。
176





