문제

다음은 엑셀 스프레드 시트에서 주조 할 수있는 객체를 얻습니다. string 또는 캐스트 가능 double. 문제는 객체가 눈에 띄게 정수라는 것을 알고 있더라도 스프레드 시트 내부에서 "일반"으로 형식으로 형식화된다는 것입니다. double. 더블을 가장 가까운 곳으로 변환하는 것은 쉽지만 int, 객체를 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");
        }
    }

편집 : Excel의 모든 숫자가 부동 소수점 번호로 표시되면 눈에 띄게 정수 이더라도이 동작을 설명 할 수 있습니다.이 경우 변환 이외의 해결책이 없습니다.

편집 : 사람들은 전환 답변을 계속 게시합니다. 이것은 질문이 관용적 인 것을 요청하기위한 것입니다 Interop 전환 답변이 아닙니다.

편집 : Chris의 답변 int i = (int)(double)GetCell(r, c) 전환이 일어나고 있기 때문에 논쟁의 여지가 있지만 내가 생각했던 것이 아닙니다. Interop.

도움이 되었습니까?

해결책

에 따르면 adrianm,

Excel 세포에는 정수와 같은 것은 없습니다. 사용 가능한 유일한 유형은 숫자, 텍스트, 논리 및 오류입니다. 숫자는 인터 로프에서 두 배로 맵핑됩니다.

그래서 대답은 그냥 두 배를 int에 던지는 것입니다.Chris 실제로 작동합니다. 이중이 시작하기 위해 정수와 같지 않으면 필요에 따라 더 적합한 변환을 원할 수 있습니다.

다른 팁

왜 안 돼 ToString() 당신의 객체, 그런 다음 구문 분석 int.Parse(...) 또는 int.TryParse(...) ?

당신은 당신을 변환 할 수 있습니다 object ~ 안으로 double 그런 다음 int, 그러나 당신은 돌봐야합니다 double 가치는보다 훨씬 큽니다 int. 그래서 당신을 더 잘 변환합니다 double ~ 안으로 long.

이 시도:

object val = /*your value*/;
double db = Convert.ToDouble(val);
long x = Convert.ToInt64(db);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top