The following gets objects from an Excel spreadsheet that are castable to string
or castable to double
. The trouble is that even if I know the object is visibly an integer, formatted as "General" inside the spreadsheet, Excel.Office.Interop always returns a double
. While it would be easy to convert the double to the nearest int
, is there a way to get an object castable to an 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");
}
}
Edit: If every number in Excel is represented as a floating point number, even if visibly an integer, then that would explain this behavior, in which case there is no solution other than conversion.
Edit: People keep posting conversion answers. This is question is meant to solicit idiomatic Interop
answers, not conversion answers.
Edit: Chris's answer in a comment int i = (int)(double)GetCell(r, c)
is arguably correct but not what I had in mind because the conversion is happening outside of Interop
.