Il seguente ottiene di oggetti da un foglio di calcolo di Excel che sono colabile a string
o colabile a double
.Il guaio è che, anche se so che l'oggetto è visibile un numero intero, formattato come "Generale", all'interno del foglio di calcolo Excel.Office.Interoperabilità restituisce sempre un double
.Mentre sarebbe facile convertire il doppio più vicino int
, c'è un modo per ottenere un oggetto colabile per 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");
}
}
Edit:Se ogni numero in Excel è rappresentato come un numero in virgola mobile, anche se visibilmente un numero intero, che potrebbero spiegare questo comportamento, nel qual caso non c'è soluzione di conversione.
Edit:Le persone a tenere il distacco di conversione risposte.Questa è la domanda che è destinata a sollecitare idiomatiche Interop
risposte, non la conversione risposte.
Edit:Chris risposta in un commento int i = (int)(double)GetCell(r, c)
è probabilmente corretto, ma non quello che avevo in mente, perché la conversione è accadendo al di fuori del Interop
.