如何从Excel单元格中获取完整值,而不是显示(舍入)值?

我有一个问题从工作表中的单元格中检索确切的值。 如果我打开文件的单元格有一个十进制数字,它只显示4位小数,但如果我点击特定单元格,值是不同的,有6位小数。 我知道这是一个应用于单元格的设置,以显示只有4位小数。

现在我试图在C#中检索单元格的数据,使用ClosedXML.Excel而不是Microsoft.Office.Interop.Excel,但唯一能够得到的是4位小数值,而不是“整数”一个,这是一个很大的问题,因为我后来计算,由于缺less2位小数,我有很大的差异。

我曾尝试使用inputSheet.Worksheet.Cell(row,col).GetDouble()Convert.ToDouble(inputSheet.Worksheet.Cell(row, col).Value) ,甚至引用“RichText”属性,或者… ToString(“0.000000”),但无论我使用什么,我只能检索4个十进制值,而不是完整的6位小数。

我看了一下库的源代码,下面是Value getter的作用:

 get { string str = this.FormulaA1; if (!XLHelper.IsNullOrWhiteSpace(str)) { string str2; string sName; if (str[0] == '{') { str = str.Substring(1, str.Length - 2); } if (str.Contains<char>('!')) { sName = str.Substring(0, str.IndexOf('!')); if (sName[0] == '\'') { sName = sName.Substring(1, sName.Length - 2); } str2 = str.Substring(str.IndexOf('!') + 1); } else { sName = this.Worksheet.Name; str2 = str; } if (this._worksheet.Workbook.WorksheetsInternal.Any<XLWorksheet>(w => (string.Compare(w.Name, sName, true) == 0)) && XLHelper.IsValidA1Address(str2)) { return this._worksheet.Workbook.Worksheet(sName).Cell(str2).Value; } object obj2 = this.Worksheet.Evaluate(str); IEnumerable enumerable = obj2 as IEnumerable; if ((enumerable != null) && !(obj2 is string)) { using (IEnumerator enumerator = enumerable.GetEnumerator()) { while (enumerator.MoveNext()) { return enumerator.Current; } } } return obj2; } string s = this.HasRichText ? this._richText.ToString() : this._cellValue; if (this._dataType == XLCellValues.Boolean) { return (s != "0"); } if (this._dataType == XLCellValues.DateTime) { return DateTime.FromOADate(double.Parse(s)); } if (this._dataType == XLCellValues.Number) { return double.Parse(s); } if (this._dataType == XLCellValues.TimeSpan) { return TimeSpan.Parse(s); } return s; } 

我注意到,当它到达string s = this.HasRichText ? this._richText.ToString() : this._cellValue; string s = this.HasRichText ? this._richText.ToString() : this._cellValue; ,如果你从来没有调用cell.RichText (所以既不用debugging器查看它),你会得到正确的值,因为this.HasRichText是错误的,因为类还没有分配正确的值。 当它( this.HasRichText )为true ,你得到this._richText.ToString() ,这是格式化的数字。 所以,如果你在访问RichText之前访问Value属性,你应该得到正确的值,无论如何,你可以使用reflection来获取_cellValue ,然后将它转换为double

 var theRealDoubleValue = Convert.ToDouble(yourCell.GetType().GetField("_cellValue", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(yourCell));