3
votes

I am dynamically creating an Excel workbook with multiple sheets using ClosedXML. I am struggling changing the sheet selected back to the first sheet in the workbook after I am done generating the content and cannot find anything in the documentation on how to change the sheet that is displayed. I have tried:

wb.Worksheet(1).Select();

This selects all of the cells in the worksheet, but it doesn't change the view back.

wb.Worksheet(1).Cells(1,1).Value = wb.Worksheet(1).Cells(1,1).Value

seems to set the value, but again doesn't change the view.

I have tried hiding the other sheets in hopes that it would auto select the visible sheets, but that does not seem to work. Any suggestions?

2
you need to be looking at the following wb.ActiveTab do a google search on the following How to set active sheet with Open XML - MethodMan
ahhh, or in the case of ClosedXML, SetTabActive() - AndrewK
While wb.TabActive will get you the active worksheet. Just loop it with list of sheets and match bool value - Chandraprakash

2 Answers

5
votes

Using ClosedXML to set the Active Sheet to the first worksheet one would use this code:

wb.Worksheet(1).SetTabActive();
2
votes

I found that Andrew K's solution did not deselect previously selected tabs. I wrote this extension to meet this requirement also:

public static class Extensions
{
    public static void SetActiveSheet(this XLWorkbook workbook, IXLWorksheet sheetToSetActive)
    {
        foreach (var sheet in workbook.Worksheets)
        {
            var isCurrentSheet = sheet.Equals(sheetToSetActive);
            sheet.SetTabActive(isCurrentSheet);
            sheet.SetTabSelected(isCurrentSheet);
        }
    }
}

Use it as follows:

var sheetToSetActive = wb.Worksheet(1);
wb.SetActiveSheet(sheetToSetActive);