Arnthor
Arnthor

Reputation: 2623

How to get a worksheet by name in .NET?

Being forced from NPOI to microsoft interop, I have to perform a task of finding a certain worksheet in workbook, and then iterate through every row of it.

In NPOI it would be simply workbook.GetSheet(sheetName);. What would be the equivalent for this in microsoft interop?

Upvotes: 22

Views: 36292

Answers (1)

Matt
Matt

Reputation: 14531

Use workbook.Sheets[sheetName];

Complete working example:

using Microsoft.Office.Interop.Excel;

class Program
{
    static void Main(string[] args)
    {
        var excelApplication = new Application();
        excelApplication.Visible = true;
        excelApplication.SheetsInNewWorkbook = 3;
        var workbook = excelApplication.Workbooks.Add();
        var worksheet = workbook.Sheets["Sheet2"];         //<--- desired method
        worksheet.Activate();
    }
}

Upvotes: 31

Related Questions