NPOI - 如何区分日期时间格式的数字 Excel-cells (c#)
NPOI - How to distinguish datetime-formatted numeric Excel-cells (c#)
背景
我有一个 Excel 文件 (xlxs),其中包含一些日期时间和小数,我想将其转换为二维字符串数组。数组中的字符串应该与用户在 excel 中输入的字符串完全一样。为此,我将 NPOI 2.2.1 版与 C# 一起使用。
请注意示例中的 A 列被格式化为 Excel!
中的日期
COLUMN A COLUMN B
2016-07-20 -46,95
2016-07-20 283,59
2016-07-20 -46,95
2016-07-20 52194,64
我有一个通用方法 ConvertCellToString() 可将单元格转换为正确的字符串表示形式:
private string GetCellAsString(ICell cell)
{
switch (cell.CellType)
{
case CellType.Boolean:
return cell.BooleanCellValue.ToString();
case CellType.Error:
return cell.ErrorCellValue.ToString();
case CellType.Formula:
return cell.CellFormula.ToString();
//ALL CELLS IN THE EXEMPEL ARE NUMERIC AND GOES HERE
case CellType.Numeric:
return cell.NumericCellValue.ToString();
case CellType.String:
return cell.StringCellValue.ToString();
case CellType.Blank:
case CellType.Unknown:
default:
return "";
}
}
但是,由于即使日期时间单元格也是数字单元格,此解决方案导致以下所有日期都被错误地表示为数字而不是日期(“21672”而不是“2016-07-20”等)
下面的方法需要区分带有日期时间的数字单元格和带有数字的单元格。有什么办法可以用 NPOI 做到这一点吗?我宁愿不求助于解析字符串,尤其是因为 NPIOs cell.ToString() returns 可怕的“2016-jan-20”格式,如果它是一个日期。
我几乎被困在这里,非常感谢您的帮助!一定有一些我找不到的明显最佳实践!
事实证明 DateUtil.IsCellDateFormatted() 可以这样使用:
case CellType.Numeric:
{
return DateUtil.IsCellDateFormatted(cell)
? cell.DateCellValue.ToString()
: cell.NumericCellValue.ToString();
}
背景
我有一个 Excel 文件 (xlxs),其中包含一些日期时间和小数,我想将其转换为二维字符串数组。数组中的字符串应该与用户在 excel 中输入的字符串完全一样。为此,我将 NPOI 2.2.1 版与 C# 一起使用。
请注意示例中的 A 列被格式化为 Excel!
中的日期COLUMN A COLUMN B
2016-07-20 -46,95
2016-07-20 283,59
2016-07-20 -46,95
2016-07-20 52194,64
我有一个通用方法 ConvertCellToString() 可将单元格转换为正确的字符串表示形式:
private string GetCellAsString(ICell cell)
{
switch (cell.CellType)
{
case CellType.Boolean:
return cell.BooleanCellValue.ToString();
case CellType.Error:
return cell.ErrorCellValue.ToString();
case CellType.Formula:
return cell.CellFormula.ToString();
//ALL CELLS IN THE EXEMPEL ARE NUMERIC AND GOES HERE
case CellType.Numeric:
return cell.NumericCellValue.ToString();
case CellType.String:
return cell.StringCellValue.ToString();
case CellType.Blank:
case CellType.Unknown:
default:
return "";
}
}
但是,由于即使日期时间单元格也是数字单元格,此解决方案导致以下所有日期都被错误地表示为数字而不是日期(“21672”而不是“2016-07-20”等)
下面的方法需要区分带有日期时间的数字单元格和带有数字的单元格。有什么办法可以用 NPOI 做到这一点吗?我宁愿不求助于解析字符串,尤其是因为 NPIOs cell.ToString() returns 可怕的“2016-jan-20”格式,如果它是一个日期。
我几乎被困在这里,非常感谢您的帮助!一定有一些我找不到的明显最佳实践!
事实证明 DateUtil.IsCellDateFormatted() 可以这样使用:
case CellType.Numeric:
{
return DateUtil.IsCellDateFormatted(cell)
? cell.DateCellValue.ToString()
: cell.NumericCellValue.ToString();
}