ClosedXML iterate Worksheets programmatically.

Nate Pet picture Nate Pet · Apr 23, 2015 · Viewed 13.5k times · Source

In my Workbook, I have 4 worksheets with different tab names. Say if they are named as follows: First, Second, Third, Fourth.

I could not find online how to iterate through each of the worksheet with say for for loop. As I am iterating, I would also like to capture the text on the Worksheet's tab (First, Second, etc.).

Answer

Kritner picture Kritner · Apr 23, 2015

You can either grab the worksheets by name or id such as:

int index = 1; // note indexes are 1 based in ClosedXML
var worksheet = workbook.Worksheet(index);

string name = "First";
var worksheet = workbook.Worksheet(name);

Note you'll only want to do the above in instances where you know the sheet name and max id (example)

or you can iterate through the collection of worksheets in a workbook as such:

foreach (IXLWorksheet worksheet in workbook.Worksheets)
{
    Console.WriteLine(worksheet.Name); // outputs the current worksheet name.
    // do the thing you want to do on each individual worksheet.
}

You can find this information in visual studio by hitting F12 on your workbook object, you'll see all of the public methods/variables you're given access too. IXLWorksheet and IXLWorksheets is what you're looking for.