为什么我在 excel 中将数值读取为字符串
Why do I get reading numeric values as string in excel
我尝试使用 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
。 '\n' 附加到值。
知道为什么有些数值显示为 string
以及为什么在值后附加“\n”吗?
看起来列的数据类型是字符串,所以如果你想检查双数据类型(假设它是 num+'\n'
格式,你可以尝试下面的代码片段.
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);
}
我尝试使用 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
。 '\n' 附加到值。
知道为什么有些数值显示为 string
以及为什么在值后附加“\n”吗?
看起来列的数据类型是字符串,所以如果你想检查双数据类型(假设它是 num+'\n'
格式,你可以尝试下面的代码片段.
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);
}