Search code examples
c#.net-6.0closedxml

ClosedXML: Is there a way I can go through every row in a Column with C#


I want to go through every column in my Excel file and save each cell in a var, So I can print it out in the Console (For testing purposes).

I know how I can do it with one Cell but not with every Column and row.

Could someone help me with this. I couldn't find any good documentation to help me.

// Creates a workbook
XLWorkbook wb = new XLWorkbook(@"C:\_Projekte\ProductMatchingChecker\ProjectData\test.xlsx");

// Creates a worksheet
IXLWorksheet worksheet = wb.Worksheets.First();

var test = worksheet.Cell("A1").Value;
Console.WriteLine(test);

Solution

  • Use Columns() method..

    // Creates a workbook
    var wb = new XLWorkbook(@"C:\_Projekte\ProductMatchingChecker\ProjectData\test.xlsx");
    
    // Creates a worksheet
    var worksheet = wb.Worksheets.First();
    
    const int targetColumn = 1; // note: first column number is 1, not 0
    
    var cellsInTargetColumn = worksheet
        .Columns()
        .FirstOrDefault(c => c.ColumnNumber() == targetColumn)
        ?.Cells()
        .ToList() ?? Enumerable.Empty<IXLCell>(); // in case target column is out of range, so foreach won't throw null-exception
    foreach (var cell in cellsInTargetColumn)
        Console.WriteLine(cell.Value.ToString());