I am writing a C# class to automate reading and writing data in an Excel spreadsheet, where that data can be of type double, int, or string. I've gotten the following method for writing data to a spreadsheet to work (using Microsoft.Office.Interop.Excel):
public void WriteMultiCellValues<T>(int row, int column, T[,] values)
{
// Create an Excel Range object encompassing the workbook's starting cell.
Range range = (Range)_worksheet.Cells[row, column];
// Get the width and height of the "values" multidimensional array.
int rows = values.GetLength(0);
int columns = values.GetLength(1);
// Resize the range to be the same size as the values array.
range = range.get_Resize(rows, columns);
// Write the range data to Excel.
range.set_Value(value: values);
}
I would like to make an analogue method which reads from a spreadsheet to a multidimensional array. But this does not work:
public T[,] ReadMultiCellValues<T>(int row, int column, int numRows, int numColumns)
{
// Create an Excel Range object encompassing the workbook's starting cell.
Range range = (Range)_worksheet.Cells[row, column];
// Resize the range to the desired dimensions.
range = range.get_Resize(numRows, numColumns);
// Read the cells' values from the spreadsheet.
return (T[,])range.Value2;
}
When run, the return statement fails because the object "range.Value2" can't be cast to an array. Does anyone know how to convert the object to a multidimensional array? Also, I'm open to solutions which don't use arrays if there is something more convenient, but it must work for data types of double, int, and string, and I would like the read and write methods to be analogous.