1

I study about Excel Read in C# but I can't Casting object[,] to double[,]

double[,] array;
    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;
    object[,] temp;
    private void button1_Click(object sender, EventArgs e)
    {
        String path = "C:\\Users\\Bob\\Desktop\\abcd.xlsx";
        //Excel.Range range;
       ReadExcelData(path);

        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Open(path, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        GetTotalValue(xlWorkSheet);


    }

in this Code GetTotalValue(xlWorksheet) is getExcelValue

 private object[,] GetTotalValue(Worksheet sheet)

    {


        Range usedRange = sheet.UsedRange;


        Range lastCell = usedRange.SpecialCells(XlCellType.xlCellTypeLastCell);

        MessageBox.Show(lastCell.Cells.Row.ToString());
        MessageBox.Show(lastCell.Cells.Column.ToString());



        Range totalRange = sheet.get_Range(sheet.get_Range("A1"), lastCell);



        return (object[,])totalRange.get_Value();

    }//end

I try Array.Copy but this method is Copy Only Array[] so I Can't Solve the this problem

BC_K
  • 27
  • 1
  • 5

1 Answers1

1

You can't cast, since double may have a different size in memory than an object reference, thus the size of the array would also be different.

C# does not have many helpers for multidimensional arrays, also LINQ mostly doesn't work here. You'll have to convert it yourself:

double[,] array = new double[temp.GetLength(0),temp.GetLength(1)];
for(int x = 0; x < array.GetLength(0); x++)
    for(int y = y; y < array.GetLength(1); y++)
        array[x,y] = (double)temp[x,y];

C# also provides a static Array.ConvertAll method, but this seems to lack overloads for multidimensional arrays.

EDIT: The second one has to be GetLength(1), not (0).

phi1010
  • 678
  • 6
  • 13