2017-08-01 32 views
0

我創建的閱讀Excel工作表函數所以在場先爭優包含的0.01的值,但是當我看到它的值,改變成一些這樣1.2999999999999999E-2指數形式時我通過DATATABLE用這個值,以便它拋出異常。所以我如何讀取準確的值避免在代碼中。 這裏是我的代碼讀取Excel工作表 -獲取指數值

 using (var sDoc = SpreadsheetDocument.Open(FileName, false)) 
     { 

      bool emptyTable = false; 

      var sheets = sDoc.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>(); 
      var relationshipId = sheets.First().Id.Value; 
      var worksheetPart = (WorksheetPart)sDoc.WorkbookPart.GetPartById(relationshipId); 
      var workSheet = worksheetPart.Worksheet; 
      var sheetData = workSheet.GetFirstChild<SheetData>(); 
      var rows = sheetData.Descendants<Row>().Skip(IgnoreRows).ToList(); 

      if (rows.Count == 0) 
      { 
       Results = dt; 
       emptyTable = true; 
      } 

      if (!emptyTable) 
      { 
       foreach (var cell in rows.ElementAt(0).Cast<Cell>()) 
       { 
        dt.Columns.Add(GetCellValue(sDoc, cell)); 
       } 

       foreach (var row in rows.Skip(1)) 
       { 
        bool emptyRow = true; 
        var tempRow = dt.NewRow(); 

        for (var i = 0; i < row.Descendants<Cell>().Count(); i++) 
        { 
         string rowValue = GetCellValue(sDoc, row.Descendants<Cell>().ElementAt(i)); 
         tempRow[i] = rowValue; 
         emptyRow = emptyRow && String.IsNullOrWhiteSpace(rowValue); 
        } 

        if (!emptyRow) 
        { 
         dt.Rows.Add(tempRow); 
        } 
        else 
        { 
         break; 
        } 
       } 
      } 

這裏是expon值 - enter image description here

enter image description here

回答

1

你可以嘗試這樣的事情(代碼塊你for循環內)

string rowValue = GetCellValue(sDoc, row.Descendants<Cell>().ElementAt(i)); 

if (i == 5) // index of column where you're expecting that value 
{ 
    decimal tempDecimal; 
    decimal.TryParse(rowValue, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out tempDecimal); 
    rowValue = tempDecimal.ToString("0.##"); 
} 
tempRow[i] = rowValue; 
emptyRow = emptyRow && String.IsNullOrWhiteSpace(rowValue) 

基本上,代碼試圖解析從特定的列(在我的例子中是5)轉換爲十進制數,然後將其轉換回帶有兩個小數點的字符串。

+0

謝謝它的工作。 – Abhay