Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Why not ToString() your object, then parse using int.Parse(...) or int.TryParse(...) ?

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top