Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open Excel File on a specific worksheet

Tags:

c#

excel

I have an Excel file with 5 worksheets and I want with c# code to open it and when it is opened I want the sheet number 3 to be activated.

How can I do that?

like image 696
Erez Avatar asked Jan 06 '10 10:01

Erez


People also ask

How do you get Excel to open on a certain sheet?

Go to a specific sheet with right click In Excel, to go to a specific sheet, you can use the right click. Place the cursor at the litter arrows at the bottom left corner of the sheet, and the right click, you can see there is a context menu popping out to show first 15 sheets.

Can you link to a specific Excel sheet?

In the Or select a place in this document box, under Cell Reference, click the worksheet that you want to link to, type the cell reference in the Type in the cell reference box, and then click OK. In the list under Defined Names, click the name that represents the cells that you want to link to, and then click OK.

How do you go to a specific worksheet?

Click the tab for the first sheet, then hold down SHIFT while you click the tab for the last sheet that you want to select. By keyboard: First, press F6 to activate the sheet tabs. Next, use the left or right arrow keys to select the sheet you want, then you can use Ctrl+Space to select that sheet.


2 Answers

Like this:

 using Excel; 

 Excel.Application excelApp = new Excel.ApplicationClass();

  // if you want to make excel visible to user, set this property to true, false by default
  excelApp.Visible = true;

 // open an existing workbook
 string workbookPath = "c:/SomeWorkBook.xls";
    Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath,
        0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
        true, false, 0, true, false, false);



// get all sheets in workbook
   Excel.Sheets excelSheets = excelWorkbook.Worksheets;

  // get some sheet
 string currentSheet = "Sheet1";
    Excel.Worksheet excelWorksheet = 
        (Excel.Worksheet)excelSheets.get_Item(currentSheet);

 // access cell within sheet
  Excel.Range excelCell = 
        (Excel.Range)excelWorksheet.get_Range("A1", "A1");

Hope this helps

MDSN info here

like image 166
Tony The Lion Avatar answered Oct 14 '22 00:10

Tony The Lion


What about something like this: (untested)

//using Excel = Microsoft.Office.Interop.Excel;

Excel.ApplicationClass app = new Excel.ApplicationClass();
Excel.Workbook workbook = app.Workbooks.Open("YourFile.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);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Sheets["Number 3"];
worksheet.Activate();
like image 33
Rubens Farias Avatar answered Oct 14 '22 01:10

Rubens Farias