简体   繁体   中英

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

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#.

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
}

Try this:

 Excel.Range r = worksheet.get_Range("*1", Missing.Value);
 for (int j = 0; j < r.Rows.Count; j++) {
    Excel.Range currentCell = r.Rows[j + 1] as Excel.Range;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM