read excel data line by line with c# .net

后端 未结 4 504
不思量自难忘°
不思量自难忘° 2020-12-30 09:00

Does anyone know how can I read an excel file line by line in c#.

I found this code which will return the data from excel and display a grindview in c#. However, I j

4条回答
  •  忘掉有多难
    2020-12-30 09:05

    Since Excel works with ranges you should first get the range of cells you would want to read. After that you can now browse through them using a for loop. You can see an example below:

        Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\myexcel.xlsx");
        Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
        Excel.Range xlRange = xlWorksheet.UsedRange;
    
        int rowCount = xlRange.Rows.Count;
        int colCount = xlRange.Columns.Count;
    
        for (int i = 1; i <= rowCount; i++)
        {
            for (int j = 1; j <= colCount; j++)
            {
                MessageBox.Show(xlRange.Cells[i, j].Value2.ToString());
            }
        }
    

    A more detailed explanation on this code block can be found here.

提交回复
热议问题