Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClosedXML iterate Worksheets programmatically.

Tags:

c#

closedxml

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.).

like image 386
Nate Pet Avatar asked Apr 23 '15 15:04

Nate Pet


1 Answers

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.

like image 164
Kritner Avatar answered Nov 01 '22 14:11

Kritner