我尝试使用NPOI库读取excel文件。
以下是代码:
public void ReadDataFromXL()
{
try
{
for (int i = 1; i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
for (int j = 0; j < row.Cells.Count(); j++)
{
var columnIndex = row.GetCell(j).ColumnIndex;
var cell = row.GetCell(j);
if (cell != null)
{
switch (cell.CellType)
{
case CellType.Numeric:
var val = cell.NumericCellValue; ;
break;
case CellType.String:
var str = cell.StringCellValue;
break;
}
}
}
}
}
catch (Exception)
{
throw;
}
}
这里是我尝试阅读的.xlsx文件的内容:
如您所见,列X和列Y是数字列。 但是当我开始使用上面的代码读取这些列时,X和Y列中的某些数值已被代码识别为字符串值。
例如,在上图中,单元格 B4 是数字类型,但在cell.CellType
上显示String
,字符串的值为31.724732480727\n
。 &#39; \ n&#39;附加到值。
知道为什么某些数值显示为string
以及为什么&#39; \ n&#39;附加到值?
答案 0 :(得分:2)
看起来该列的数据类型是String,因此如果要检查double数据类型(假设它将采用num+'\n'
格式,则可以尝试以下代码片段。< / p>
String number = "1512421.512\n";
double res;
if (double.TryParse(number.Substring(0, number.Length - 1), out res))
{
Console.WriteLine("It's a number! " + res);
}