Reputation: 11279
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
.
Upvotes: 1
Views: 2437
Reputation: 11279
According to adrianm
,
There is no such thing as an integer in excel cells. The only types available are Number, Text, Logical and Error. Number is mapped to Double in the interop.
So the answer is to just cast the double to an int, which asChris
points out actually works. Note that if the double is not equal to an integer to begin with, you might want to do a more suitable conversion according to your need.
Upvotes: 1
Reputation: 26209
You can convert your object
into double
and then into int
, but you should take care as double
value is much bigger than int
. so better convert your double
into long
.
Try This:
object val = /*your value*/;
double db = Convert.ToDouble(val);
long x = Convert.ToInt64(db);
Upvotes: 0
Reputation: 3694
Why not ToString()
your object, then parse using int.Parse(...)
or int.TryParse(...)
?
Upvotes: 0