简体   繁体   中英

Open Excel File on a specific worksheet

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 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

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();

If wanting to present visual feedback to the User, these two statements will set the activated sheet and select the range accordingly:

Consider including the following statement immediately prior to initializing the Excel.Range...

// Set Active sheet in Excel

excelWorksheet.Activate()

Also consider the following statement immediately after initializing the Excel.Range...

// Set Active range in Excel

excelCell.Activate()

public static Workbook openExternalWorkBook(String fileName)
    {
        Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();            
        excel.Visible = false;
        return excel.Workbooks.Open(fileName, false);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM