打开Excel工作表

时间:2014-04-17 06:26:42

标签: c# excel

如何打开Excel工作表的特定工作簿?目前我正在使用

System.Diagnostics.Process.Start(path);

但它只是打开excel。我想集中讨论一个特定的工作表。

怎么做?是否可以使用

Microsoft.Office.Interop.Excel;

1 个答案:

答案 0 :(得分:4)

在项目中添加对Microsoft.Office.Interop.Excel的引用,您可以使用下一个代码作为基础

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