Reputation: 543
I'm currently working on a spreadsheet reader that needs to read the second worksheet in the ExcelFile. I've looked only but can't find anywhere that references how to set the activeworksheet.
Currently my active worksheet is set like this:
ExcelWorksheet worksheet = excelFile.Worksheets.ActiveWorksheet;
When debugging, i noticed that it's reading the first worksheet out of the two, when i need it to be reading the second file.
How would i be able to set the active worksheet to an index of 1 rather than an index of 0.
Thanks
UPDATE:
I fixed this by querying using Linq, that went through the ExcelFile Worksheets and setting the worksheet index. Example code below:
ExcelWorksheet worksheet = excelFile.Worksheets.Where(x => x.Index = 1).SingleOrDefault();
Upvotes: 0
Views: 1351
Reputation: 4381
First note that active worksheet is the one selected when file is opened with some Excel application (like MS Excel), see ActiveWorksheet property's help page.
You can set any sheet to be an active one and usually (by default) it's the first one in the workbook, so that is why you're accessing the first sheet with it. But in order to access any sheet that you want you can retrieve it from the Worksheets collection through indexer, like the following:
ExcelWorksheet firstSheet = excelFile.Worksheets[0];
ExcelWorksheet secondSheet = excelFile.Worksheets[1];
Or with the sheet's name, like the following:
ExcelWorksheet firstSheet = excelFile.Worksheets["Sheet1"];
ExcelWorksheet secondSheet = excelFile.Worksheets["Sheet2"];
See Worksheets properties on help page.
Upvotes: 1