3

I have an array and I need to put the elements in one row, every element of the array should be in a different cell.

foreach (var cell in range.Cells())
        {
            int index = 0;
            cell.Value = arrayCompany[index];
            index++;

            if (index == count)
            {
                break;
            }
        }

My array has 10 elements and the excel file generates one row but in all 10columns, cell value is the last element of the array. I want each element to be in a different column. A1=arrayCompany[0],B1=arrayCompany[1] ... 10thcolumn = arrayCompany[9]

3
  • Please detail what you want to occur, what the current code does and how i differs form what you expect. Some samples / examples would be even better. Commented Jul 10, 2017 at 12:04
  • my array has 10 elements and the excel file generates one row but in all 10columns, cell value is the last element of the array. I want each element to be in a different column. A1=arrayCompany[0],B1=arrayCompany[1] ... 10thcolumn = arrayCompany[9] Commented Jul 10, 2017 at 12:10
  • Please update your post rather than adding comments. Commented Jul 10, 2017 at 12:11

3 Answers 3

8

You can use

cell.InsertData(data: yourEnumerable, transpose: true);

Notice the transpose parameter, which allows you to insert your values in a row. By default, values of an enumerable would be inserted below each other.

Sign up to request clarification or add additional context in comments.

2 Comments

Transpose is main point to note, I was erroring out for 30mins+ because I missed the transpose and data was getting overwritten.
@surpavan I updated the answer to highlight the transpose parameter.
1
            for (int index = 0; index < 10; index++)
            {
                var cell = range.Cell(1, index + 1);
                cell.Value = arrayCompany[index];
            }

This is working, but I guess there is a more clean solution for the problem.

Comments

0

I've used this:

worksheet.Cell(x, y).Value = toExport.AsEnumerable();

Where my toExport variable is a list of objects. It does not only enumerate all properties to columns, it also inserts every instance in a new row.

This might also work with an array.

1 Comment

I have tried this solution, but it's inserting every element in a new row. I want to insert all the elements in one single row which means each element in different column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.