Lo siguiente obtiene objetos de una hoja de cálculo de Excel que se pueden lanzar a string
o castible con double
. El problema es que incluso si sé que el objeto es visiblemente un entero, formateado como "general" dentro de la hoja de cálculo, Excel.Office.Enterop siempre devuelve un double
. Si bien sería fácil convertir el doble al más cercano int
, ¿hay alguna forma de obtener un objeto castigable a un 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");
}
}
Editar: si cada número en Excel se representa como un número de punto flotante, incluso si es visiblemente un entero, entonces eso explicaría este comportamiento, en cuyo caso no hay otra solución que no sea la conversión.
Editar: la gente sigue publicando respuestas de conversión. Esta es la pregunta está destinada a solicitar idiomática Interop
Respuestas, no respuestas de conversión.
Editar: la respuesta de Chris en un comentario int i = (int)(double)GetCell(r, c)
posiblemente sea correcto pero no lo que tenía en mente porque la conversión está ocurriendo fuera de Interop
.