即使它是一个整数,Excel.Office.Interop也会返回double

以下内容从Excel电子表格中将对象转换为可以转换为string或可转换为double 。 问题是,即使我知道该对象明显是一个整数,格式为电子表格中的“常规”,Excel.Office.Interop总是返回一个double 。 虽然将double转换为最接近的int很容易,但是有没有办法将一个对象转换为int

  // returns null if the cell is empty // returns an object castable to a string if it is a string // returns an object castable to a double if it is a floating point or integer number internal object GetCell(int row, int column) { if ((row != 0) && (column != 0) && (worksheet != null)) { string cellName = ExcelCellReference(row, column); Microsoft.Office.Interop.Excel.Range oneCellRange; oneCellRange = worksheet.get_Range(cellName, cellName); object oneObject; // contrary to MSDN, the value Empty, checkable with method IsEmpty() // does not work if the cell was empty. // instead, what happens is that null is returned. oneObject = (object) oneCellRange.get_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault); return oneObject; } else { if (worksheet == null) throw new Exception("null worksheet reference"); else throw new Exception("invalid argument"); } } 

编辑:如果Excel中的每个数字都表示为一个浮点数,即使可见一个整数,那么这也可以解释这种行为,在这种情况下除了转换之外没有解决scheme。

编辑:人们不断发布转换的答案。 这是问题是为了招揽惯用的Interop答案,而不是转换的答案。

编辑:克里斯在评论中的答案int i = (int)(double)GetCell(r, c)可以说是正确的,但不是我想到的,因为转换发生在Interop之外。

为什么不ToString()你的对象,然后parsing使用int.Parse(...)int.TryParse(...)

你可以把你的object转换成double ,然后转换成int ,但是你应该小心,因为double值比int大得多。 所以更好地转换你的double long

尝试这个:

 object val = /*your value*/; double db = Convert.ToDouble(val); long x = Convert.ToInt64(db); 

根据adrianm

在Excel单元格中没有这样的整数。 唯一可用的types是数字,文本,逻辑和错误。 数字在互操作中映射到Double。

所以答案就是把这个double加到int,正如Chris指出的那样。 请注意,如果double不等于一个整数,那么您可能需要根据需要进行更合适的转换。