how to set values to a two-dimensional Excel range?

社会主义新天地 提交于 2019-12-07 09:09:27
Elad

One cell or 1dim array can be set via one of the following:

Range range = SetRange();//Let's say range is set between A1 to D1
object[] args = {1, 2, 3, 4 }; 

//Directly
range.Value = args;

//By Reflection
range.GetType().InvokeMember("Value", System.Reflection.BindingFlags.SetProperty, null, range, args);

A 2dim array cannot be directly set, so one has to use the reflection flow to set a matrix of values. This matrix has to be built before the set, like this:

Range range = SetRange();//Let's say range is set between A1 to C5
int rows = 5;
int columns = 3;
object[,] data = new object[rows, columns];
for (int i = 0; i < rows; i++)
{
    for (int j = 0; j < columns; j++)
    {
        //Here I build the inside Array[,]
        string uniqueValue = (i + j).ToString();
        data[i, j] = "Insert your string value here, e.g: " + uniqueValue;
    }
}
object[] args = { data };
range.GetType().InvokeMember("Value", System.Reflection.BindingFlags.SetProperty, null, range, args);

As for your issue, all the range set to null, I think this is due to wrong arguments.

Indeed why the Type.Missing in the arguments list?

Hence this should be a step in the right direction:

object[] args = { list.ToArray() };
test.GetType().InvokeMember("Value", System.Reflection.BindingFlags.SetProperty, null, test, args);

Moreover list.ToArray will only generate an array of arrays not a matrix, so you should build your matrix differently, e.g.:

object[,] data = new object[14, 2];
int row = 0;
foreach (KeyValuePair<string, string> item in testCase.Steps)
{
    //Here I build the inside Array[,]
    data[row, 0] = item.Key;
    data[row, 1] = item.Value;
    ++row;
}
object[] args = { data };

And what's the rational behind the use of InvokeMember instead of a simpler:

test.Value = data;

?

Hope this helps...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!