Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining Excel worksheet reference by worksheet name via C#

I'm currently obtaining a handle to a Excel worksheet by using the below C# code:

Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(15);
//Get the worksheet "SubSignOff" number

Is there any way that I can obtain the same by using the worksheet name "SubSignOff" ?

like image 848
Chapax Avatar asked Mar 22 '10 09:03

Chapax


People also ask

How do you reference a worksheet name in Excel?

To reference a cell or range of cells in another worksheet in the same workbook, put the worksheet name followed by an exclamation mark (!) before the cell address. For example, to refer to cell A1 in Sheet2, you type Sheet2! A1.

Can I reference a sheet name in an Excel formula?

Notes: The worksheet name comes before the cell address, followed by an exclamation mark ! . If the worksheet name includes spaces, enclose it in single quotation marks ' .

How do I make a sheet name dynamic in Excel?

Consider a simple dynamic reference to Sheet2 using the INDIRECT in a formula like this: = INDIRECT ( $B$5 & "!" & "A1" )) If we change the sheet name in B5 to another (valid) name, INDIRECT will return a reference to A1...


1 Answers

Instead of the using Excel.Workbook.Sheets collection, it's easier to access the Excel.Workbook.Worksheets collection, that way you can utilize early binding.

In your case, it could look something like the following:

Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;

Excel.Workbook workbook = excelApp.Workbooks.Open("C:\MyWorkbook.xls",
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
    Type.Missing, Type.Missing, Type.Missing, Type.Missing);

// The key line:
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets["SubSignOff"];

Hope this helps...

like image 182
Mike Rosenblum Avatar answered Oct 18 '22 04:10

Mike Rosenblum