Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read excel file row by row, cell by cell C#

Tags:

c#

excel

I want (as title states) to programmatically read values from an Excel file. Row by row and then cell by cell, to have the freedom of creating custom collections out of cell's data.

This questions helped me.

But I need more flexible code. Can I for example write (* is just for all columns)

            Range range1 = worksheet.get_Range("*1", Missing.Value)

            foreach (Range r in range1)
            {
                string user = r.Text;
                string value = r.Value2;
            }

And iterate all cells in row 1 as long as there is next. There must be some elegant way to iterate through rows and cells in C#.

like image 230
eomeroff Avatar asked Mar 01 '14 20:03

eomeroff


People also ask

How do I select specific rows in Excel?

Select one or more rows and columns Or click on any cell in the column and then press Ctrl + Space. Select the row number to select the entire row. Or click on any cell in the row and then press Shift + Space. To select non-adjacent rows or columns, hold Ctrl and select the row or column numbers.

How do you pull data from a range in Excel?

Select a cell in the database. On the Excel Ribbon's Data tab, click the Advanced button. In the Advanced Filter dialog box, choose 'Copy to another location'. For the List range, select the column(s) from which you want to extract the unique values.


1 Answers

You can rely on the Rows/Columns properties and then iterate through all the contained ranges (Cells). Sample code:

Range range1 = worksheet.Rows[1]; //For all columns in row 1
//Range range1 = worksheet.Columns[1]; //for all rows in column 1

foreach (Range r in range1.Cells) //range1.Cells represents all the columns/rows
{
    // r is the range of the corresponding cell
}
like image 145
varocarbas Avatar answered Sep 26 '22 06:09

varocarbas