using c# to select a worksheet in excel

久未见 提交于 2019-12-05 05:20:41

You can use the following code :

Worksheet sheet = (Worksheet)xlApp.Worksheets[1];
sheet.Select(Type.Missing);

or

sheet.Activate();

I have used this code and it works fine for me.

Are your properties initialized?

If they are, you should probably be able to achieve what you are trying to by either of those:

xlApp.ActiveWorkbook.Sheets[1].Activate();
xlWorkbook.Sheets[1].Activate();
xlSheet.Activate();

If they are not, you should initialize at least xlApp property to Application object you're working with and then use the code above. You can initialize first two objects by using the code below.

xlApp = new Microsoft.Office.Interop.Excel.Application();
Workbooks xlWorkbooks = xlApp.Workbooks;
xlWorkbook = xlWorkbooks.Open(@"C:\filename.xlsx");
l--''''''---------''''''''''''

Here is what I did and it works!

Excel.Worksheet xlWorkSheetFocus = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
xlWorkSheetFocus.Activate();
André Bravo Ferreira

You can do it both ways:

Excel.Application xlApp;
Excel.Worksheet xlWorksheet;
  1. xlWorksheet = xlApp.Worksheets.get_Item(1);

  2. xlWorksheet = xlApp.Worksheets[1];

xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(2);

OR

xlWorkSheet =(Worksheet)xlWorkBook.Sheets["SheetName"];

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!