2016-03-05 14 views
0

我尝试使用NPOI库读取excel文件。为什么我会在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文件,我尝试阅读的内容:

enter image description here

正如你可以看到列X和列Y的数值列。 但是当我开始使用上面的代码读取这些列时,X和Y列中的一些数值已被代码识别为字符串值。

例如,在画面中的细胞B4以上是数字类型,但是,上cell.CellType它显示String和字符串的值是31.724732480727\n。 '\ n'被附加到值。

任何想法为什么一些数值显示为string和为什么'\ n'附加到值?

+0

'\ n'是一个换行符,是从某处复制/粘贴的数字,还是手动输入的? – dognotdog

+0

如果您刚刚从excel中读取数据,您可能需要使用OleDbConnection类。 –

+0

@dognotdog它是从file.The文件序列化 – Michael

回答

1

它看起来像列是字符串的,所以如果你想检查为双数据类型(假设它的将是在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); 
     } 
+0

但想知道它从哪里来 - 'n' – Michael

+0

这个数据来自哪里?可能是,它可能来自一个电子表格,其中dat一个是复制/粘贴,这将解释新行。 –

+0

好的,但为什么NPOI库将它作为数据的一部分(新行)? – Michael

相关问题