逐行读取excel文件,逐个单元格C#

时间:2014-03-01 20:20:27

标签: c# excel

我希望(作为标题状态)以编程方式从Excel文件中读取值。逐行,然后逐个单元格,可以自由地从单元格数据中创建自定义集合。

questions帮助了我。

但我需要更灵活的代码。我可以写一下(*仅适用于所有列)

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

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

只要有下一个,就迭代第1行中的所有单元格。 必须有一些优雅的方法来迭代C#中的行和单元格。

2 个答案:

答案 0 :(得分:6)

您可以依赖Rows / Columns属性,然后遍历所有包含的范围(Cells)。示例代码:

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
}

答案 1 :(得分:1)

试试这个:

 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;
 }
相关问题