Varghese
Varghese

Reputation: 151

How to open the corresponding excel sheet in a workbook using c#

My code opens the first sheet of an excel. My target is to open the sheet selected in combobox. Do anyone can help me to find solution:

My Code:

 string currsheet = comboBox1.SelectedItem.ToString();
 Microsoft.Office.Interop.Excel.Application xap = new Microsoft.Office.Interop.Excel.Application();
 xap.Visible = true;
 Microsoft.Office.Interop.Excel.Workbook wk = xap.Workbooks.Open(path3,0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
 Microsoft.Office.Interop.Excel.Sheets excelsheet = wk.Worksheets;
 Microsoft.Office.Interop.Excel.Worksheet wsh = (Worksheet)excelsheet.get_Item(currsheet);

Upvotes: 1

Views: 2727

Answers (1)

Daniel Möller
Daniel Möller

Reputation: 86600

By sheet name

Microsoft.Office.Interop.Excel.Worksheet wsh = (Worksheet)excelsheet["SheetName"];

By index (starting with 1 - first sheet)

Microsoft.Office.Interop.Excel.Worksheet wsh = (Worksheet)excelsheet[1];

Just use one of those values in your combobox. If you want to populate your combo box with available sheets, you can go throug Worksheets

foreach (Worksheet Sh in excelsheet)
{
    Combobox.Items.Add(Sh.Name); 
}

Then, the combobox selected value will be already a sheet name, you get by:

Microsoft.Office.Interop.Excel.Worksheet wsh = (Worksheet)excelsheet[Combobox.SelectedValue]; //I'm not sure if combobox value is got like this, but the excel part is ok.

Upvotes: 2

Related Questions