Home » excel » c# – How to put array into excel range

c# – How to put array into excel range

Posted by: admin May 14, 2020 Leave a comment

Questions:

I know how to write single cell into excel but when im trying it on array excel sheet is filling with only last value

this is my range

 Excel.Range ServiceName = (Excel.Range)_sheet.get_Range(_sheet.Cells[38, "B"] as Excel.Range, _sheet.Cells[45, "B"] as Excel.Range);

_ServiceName is List which contains 1,2,3,4,5,6

for (int i = 0; i < _ServiceName.Count; i++)
            {
                ServiceNameArray[0, i] = _ServiceName[i];

            }

this i my trying to write into excel but as i said it there is only last item (6) in excel book

 for (int i = 0; i < _ServiceName.Count; i++)
            {
                ServiceName.set_Value(Type.Missing, ServiceNameArray[0,i]);
            }

does anyone have an idea?

How to&Answers:

Davide Piras is right. And you’re doing a few other strange things there, I can elaborate by request.

For now I just want to point out that you can directly assign the .Value property of a Range to an array:

ServiceName.Value2 = _ServiceName.toArray();

This is much, much faster for bigger amounts of data.

(Side note: If you want to do the same with Formulas, for some strange reason you have to take an extra step (doubling the time):

range.Formula = array;
range.Formula = range.Formula;

unless there is a better way I don’t know about yet.)

Answer:

I see you looping on the ServiceName array to get all values one after the other but not see you changing the focused cell inside the cellrange at every loop iteration. Of course, I would say, you see only the last value, because you are writing all values one over the other always in the same place.