문제

I have a Microsoft.Office.Interop.Excel.Range Object obtained as shown:

Dim maxRow As Integer = currentSheet.UsedRange.Rows.Count
currentSheet.Range("A2").Resize(maxRow-1, 2).Value

and I'm trying to convert that to a 2 dimensional array of doubles, but if I do:

Dim arrayData(,) As Double = currentSheet.Range("A2").Resize(maxRow - 1, 2).Value

I get the following error:

Additional information: Unable to cast object of type 'System.Object[,]' to type 'System.Double[,]'.

Is there a simple way to obtain the data from a spreadsheet as an array of doubles? I could loop over each element in the array, but it seems like that shouldn't be necessary.

도움이 되었습니까?

해결책

Use Array.Copy()

Dim arrayData(,) As Double
Dim objData(,) As Object = currentSheet.Range("A2").Resize(maxRow - 1, 2).Value
Array.Copy(objData, arrayData, objData.Length)

By the way I found this by putting convert 2d object double into a search engine... How can I quickly up-cast object[,] into double[,]?

Edit

I just tried it on my own Excel sheet and it works. One thing I should add is that I needed to specify the bounds of the destination array when dimensioning it.

'Dim objData(,) As Object = xlSheet.Range("C6:E14").Value ' either way works
Dim objData(,) As Object = xlSheet.Range("C6").Resize(9, 3).Value
Dim dblData(objData.GetUpperBound(0) - 1, objData.GetUpperBound(1) - 1) As Double
Array.Copy(objData, dblData, objData.Length)

Can you inspect your Object(,) at runtime to make sure there is data inside it? Also, everything needs to be castable to Double.

다른 팁

This is a C# sample, but you shouldn't have problems converting it to vb.

object[,] arrWks = (object[,])enuWorksheet.UsedRange.get_Value(XLS.XlRangeValueDataType.xlRangeValueDefault);

So int your case, instead of .Value, use get_Value method.

Then when iterating through array, remember to check for nulls:

object objKom = arrWks[intRow, intCol];
string strKom = objKom == null ? "" : objKom.ToString();

Hope this helps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top