NPOI – 如何区分date时间格式的数字Excel单元格(c#)

背景

我有Excel文件(xlxs)与一些date时间和小数,我想转换成一个二维string数组。 数组中的string看起来应该和用户input到excel中一样。 为此,我使用C#使用NPOI 2.2.1版本。

请注意,示例中的列A在Excel中被格式化为date!

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()将单元格转换成适当的string表示forms:

  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 ""; } } 

但是,因为即使date时间单元格是数字单元格,此解决scheme导致在下面的所有date被错误地表示为数字而不是date(“21672”,而不是“2016-07-20”等)

下面的方法需要区分date时间与数字时间的数字单元格。 有没有这样做NPOI? 我宁愿不要求parsingstring,尤其是因为NPIOs cell.ToString()返回可怕的“2016-jan-20”格式,如果它是一个date。

我几乎卡在这里,所以帮助将不胜感激! 必须有一些明显的最佳做法,我只是找不到!

结果可以这样使用DateUtil.IsCellDateFormatted():

  case CellType.Numeric: { return DateUtil.IsCellDateFormatted(cell) ? cell.DateCellValue.ToString() : cell.NumericCellValue.ToString(); }