在特定工作表上打开Excel文件

时间:2010-01-06 10:40:55

标签: c# excel

我有一个包含5个工作表的Excel文件,我想用c#代码打开它 当它打开时,我希望激活第3号纸张。

我该怎么做?

4 个答案:

答案 0 :(得分:26)

像这样:

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

希望这有帮助

MDSN信息here

答案 1 :(得分:4)

这样的事情:(未经测试)

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

答案 2 :(得分:1)

如果想要向用户提供视觉反馈,这两个语句将设置激活的工作表并相应地选择范围:

在初始化Excel.Range ...

之前,请考虑包含以下语句

//在Excel中设置活动工作表

excelWorksheet.Activate()

在初始化Excel.Range ...

后,请立即考虑以下语句

//在Excel中设置活动范围

excelCell.Activate()

答案 3 :(得分:0)

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