我有此Excel列:
格式化为日期数据格式:
如果我尝试读取DateTime值,则会得到NullReferenceException
。
您知道这里有什么问题以及如何解决吗?是否可以将数字转换为DateTime?例如,当我更改为数字格式时,31/12/9999是2958465。
输入字符串扩展名
public static class NpoiExtension
{
public static string GetStringValue(this ICell cell)
{
switch (cell.CellType)
{
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(cell))
{
try
{
return cell.DateCellValue.ToString();
}
catch (NullReferenceException)
{
// https://stackoverflow.com/questions/15040567/c-xlsx-date-cell-import-to-datatable-by-npoi-2-0
//var prevCulture = Thread.CurrentThread.CurrentCulture;
//CultureInfo customCulture = new CultureInfo("en-GB", false);
//Thread.CurrentThread.CurrentCulture = customCulture;
string dateOutput = cell.DateCellValue.ToString();
//Thread.CurrentThread.CurrentCulture = prevCulture;
return dateOutput;
}
}
else
{
return cell.NumericCellValue.ToString();
}
case CellType.String:
return cell.StringCellValue;
case CellType.Boolean:
return cell.BooleanCellValue.ToString();
default:
return string.Empty;
}
}
}
答案 0 :(得分:0)
我在这里How do I convert an Excel serial date number to a .NET DateTime?找到了解决方案,因此将其添加到我的方案中。
public static string GetStringValue(this ICell cell)
{
switch (cell.CellType)
{
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(cell))
{
try
{
return cell.DateCellValue.ToString();
}
catch (NullReferenceException)
{
return DateTime.FromOADate(cell.NumericCellValue).ToString();
}
}
return cell.NumericCellValue.ToString();
case CellType.String:
return cell.StringCellValue;
case CellType.Boolean:
return cell.BooleanCellValue.ToString();
default:
return string.Empty;
}
}
答案 1 :(得分:0)
每当将单元格定义为数字时,另一个获取日期时间的简洁方法就是获取单元格的数值:
DateTime.FromOADate(cell.NumericCellValue);
完整的示例:
private ICell GetCellValue(string position)
{
var cr = new CellReference(position);
var row = m_Sheet.GetRow(cr.Row);
return row.GetCell(cr.Col);
}
public DateTime? GetCellDateValue(string position)
{
ICell cellValue = GetCellValue(position);
if (cellValue == null)
{
// Cell doesn't have any value
return null;
}
if (cellValue.CellType == CellType.Numeric)
{
return DateTime.FromOADate(cellValue.NumericCellValue);
}
return cellValue.DateCellValue;
}