在C#中打开MS Excel工作表

时间:2010-06-18 00:58:17

标签: c# excel

我知道我们可以使用C#打开MS Excel的特定工作表,提供工作表编号(1,2,3 ..)或名称(sheet1,sheet2,sheet3 ...)

我有一个excel文件,有2张,1。值,2。结果

有没有办法打开一张给出纸张名称的纸张,即“值”而不是1或[s | S] heet1在C#??

我看过旧帖子,但没有发现任何有用的东西......

所以,我要做的是,使用其用户定义的名称(值)而不是系统定义的名称(1或[s | S] heet1)打开Excel工作表

任何输入都将非常感谢!

2 个答案:

答案 0 :(得分:3)

在项目中添加对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);

答案 1 :(得分:0)

@volody,谢谢!你的帖子帮了很多忙。 我从你的工作表声明部分中取出并将我改为以下内容:

        Excel.Application excelApplication;
        Excel.Worksheet excelWorksheet;
        Excel.Workbook excelWorkbook;
        Excel.Range range;

        excelApplication = new Excel.Application();

        excelWorkbook = (Excel.Workbook)(excelApplication.Workbooks.Open(
            <FILENAME>,
            Type.Missing, true, Type.Missing, Type.Missing, Type.Missing,
            true, Type.Missing, Type.Missing, false, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing));

        excelWorksheet = (Excel.Worksheet)excelWorkbook.Worksheets[<WORKSHEETNAME>];

上面的代码有助于打开带有用户定义名称的Excel工作表。例如,要打开名为Test而不是Sheet1的工作表。

  • 的Ivar