O seguinte obtém objetos de uma planilha do Excel que podem ser convertidos para string
ou moldável para double
.O problema é que mesmo sabendo que o objeto é visivelmente um número inteiro, formatado como "Geral" dentro da planilha, o Excel.Office.Interop sempre retorna um double
.Embora fosse fácil converter o dobro para o mais próximo int
, existe uma maneira de obter um objeto convertível em um 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:Se cada número no Excel fosse representado como um número de ponto flutuante, mesmo que visivelmente um número inteiro, isso explicaria esse comportamento, caso em que não há outra solução além da conversão.
Editar:As pessoas continuam postando respostas de conversão.Esta pergunta destina-se a solicitar expressões idiomáticas Interop
respostas, não respostas de conversão.
Editar:A resposta de Chris em um comentário int i = (int)(double)GetCell(r, c)
é indiscutivelmente correto, mas não o que eu tinha em mente porque a conversão está acontecendo fora de Interop
.