Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a worksheet by name in .NET?

Tags:

.net

excel

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?

like image 689
Arnthor Avatar asked Nov 09 '11 15:11

Arnthor


People also ask

How do you select a worksheet in C#?

Application. ActiveWorkbook. Sheets[1]). Select();

How do I get a list of sheet names?

Right-click the text box to select it, press Ctrl+K to launch the Insert Hyperlink dialog box, select Place in This Document (under the Link to menu), scroll down to Defined Names, select TOC, and press OK. These actions will create a clickable button that will return you to your table of contents.


1 Answers

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();
    }
}
like image 98
Matt Avatar answered Sep 30 '22 19:09

Matt