简体   繁体   中英

Open an excel worksheet

How to open a specific workbook of an excel sheet? Currently I am using

System.Diagnostics.Process.Start(path);

but it just opens that excel. I would like to focus in to a specific worksheet.

How to do it? Is it possible using

Microsoft.Office.Interop.Excel;

Add reference to Microsoft.Office.Interop.Excel in your project and you can use next code as base

using Excel=Microsoft.Office.Interop.Excel; 


Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;

//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = false;
oXL.DisplayAlerts = false; //prevents message from popping up

try
{
    //Get a new workbook.
    oWB = (Excel._Workbook)(oXL.Workbooks.Open(filename, 
        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));

    oSheet = (Excel._Worksheet)oWB.ActiveSheet;

    int nCounter = 1;
    oSheet.Copy(oSheet, Type.Missing);
    Excel._Worksheet oSheetGame = (Excel._Worksheet)oWB.Worksheets["MyTemplate"];
    oSheetGame.Name = "MyNewWorksheetName";

    //do something with worksheet

    ((Excel._Worksheet)oWB.Sheets["MyTemplate"]).Delete(); // delete template
    ((Excel._Worksheet)oWB.Worksheets["MyNewWorksheetName"]).Activate();

}
catch (Exception e)
{
    //throw e;
    throw;
}
finally
{
    //Make sure Excel is visible and give the user control
    //of Microsoft Excel's lifetime.
    oXL.Visible = true;
    oXL.UserControl = true;
}

oXL.Save(Type.Missing);

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