在excel文檔中,數字、日期類型數據在編輯後會變成numeric格式
導致在讀取過程中,如果按照原來格式讀取會遇到問題
故添加以下函數進行判斷
/// <summary>
/// 獲取字符串格式的值
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private string GetCellStringValue(ICell cell)
{
try
{
if (cell == null || cell.CellType == CellType.Blank)
{
return null;
}
string result;
switch (cell.CellType)
{
case CellType.Numeric:
result = cell.NumericCellValue.ToString(CultureInfo.InvariantCulture);
break;
default:
result = cell.StringCellValue?.Trim();
break;
}
return result;
}
catch
{
return null;
}
}
/// <summary>
/// 獲取日期格式的值
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private DateTime? GetCellDateTimeValue(ICell cell)
{
try
{
if (cell == null || cell.CellType == CellType.Blank)
{
return null;
}
DateTime? result;
switch (cell.CellType)
{
case CellType.Numeric:
result = cell.DateCellValue;
break;
case CellType.String:
result = DateTime.Parse(cell.StringCellValue);
break;
default:
result = null;
break;
}
return result;
}
catch
{
return null;
}
}
/// <summary>
/// 獲取數字格式的值
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private double? GetCellNumericValue(ICell cell)
{
try
{
if (cell == null || cell.CellType == CellType.Blank)
{
return null;
}
double? result;
switch (cell.CellType)
{
case CellType.Numeric:
result = cell.NumericCellValue;
break;
case CellType.String:
result = double.Parse(cell.StringCellValue);
break;
default:
result = null;
break;
}
return result;
}
catch
{
return null;
}
}