DeeWBee
DeeWBee

Reputation: 695

How to read from multiple cells in Excel using C# Windows Forms

I wanted to add Windows Forms controls to an excel document I created.

To do so, I created a new project using the Office 2010 Excel 2010 Workbook template in VS 2010 (C#). All I am trying to do is copy data from multiple cells and write them to a text file.

Whenever I put all of the cells I want under a single Name Space, and then try to read the "Value2", I just get "System.Object[,]".

All I have done so far is added a radioButton to Sheet 1 and created an event handler. Past that I am not sure what to do.

Upvotes: 1

Views: 936

Answers (1)

D Stanley
D Stanley

Reputation: 152624

The Value2 property of a range comes back as a 2-d array of values. To access the values just loop through the array:

object[,] values = range.Values2;
for(int i = 0; i < values.Length(0); i++)
    for(int j = 0; j < values.Length(1); j++)
    {
        object cellValue = values[i,j];
        // do something with the value
    }

Upvotes: 3

Related Questions