'Reading from Excel File using ClosedXML

My Excel file is not in tabular data. I am trying to read from an excel file. I have sections within my excel file that are tabular.

I need to loop through rows 3 to 20 which are tabular and read the data.

Here is party of my code:

     string fileName = "C:\\Folder1\\Prev.xlsx";
     var workbook = new XLWorkbook(fileName);
     var ws1 = workbook.Worksheet(1); 

How do I loop through rows 3 to 20 and read columns 3,4, 6, 7, 8? Also if a row is empty, how do I determine that so I can skip over it without reading that each column has a value for a given row.



Solution 1:[1]

Here's my jam.

var rows = worksheet.RangeUsed().RowsUsed().Skip(1); // Skip header row
foreach (var row in rows)
{
    var rowNumber = row.RowNumber();
    // Process the row
}

If you just use .RowsUsed(), your range will contain a huge number of columns. Way more than are actually filled in!

So use .RangeUsed() first to limit the range. This will help you process the file faster!

You can also use .Skip(1) to skip over the column header row (if you have one).

Solution 2:[2]

I prefer using RowsUsed() method to get a list of only those rows which are non-empty or has been edited by the user. This way I can avoid making emptiness check while processing each row.

I'm not sure if this solution will solve OP's problem. But this code snippet can process 3rd to 20th row numbers out of all the non-empty rows as I've filtered the empty rows already before starting the process. Filtering the non-empty rows before processing can affect the count of rows which will get processed.

But I feel that RowsUsed() method is very helpful in any general scenario when you are processing the rows of an excel sheet.

string fileName = "C:\\Folder1\\Prev.xlsx";
using (var excelWorkbook = new XLWorkbook(fileName))
{
    var nonEmptyDataRows = excelWorkbook.Worksheet(1).RowsUsed();

    foreach (var dataRow in nonEmptyDataRows)
    {
       //for row number check
       if(dataRow.RowNumber() >=3 && dataRow.RowNumber() <= 20)
       {
           //to get column # 3's data
           var cell = dataRow.Cell(3).Value;
       }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2