简体   繁体   中英

Excel/C# - Get worksheet id by name?

I currently have a worksheet with several sheets :
Sheet_Alpha | Sheet 2 | Sheet_Beta | Sheet 4 | Sheet 5 | Sheet_Delta

How I can recover them id according to their name? To be then able to select the sheet which I want with : Worksheets.get_Item()

Is it possible? I looked for a moment and I find nothing to do it.

Thanks :)

You can first transfer info about all the sheets of the workbook to a List as below

string name = "xxx";
List<Worksheet> lstSheet = new List<Worksheet>();
foreach (Worksheet ws in MyBook.Sheets)
{
    lstSheet.Add(ws);
}

And then access the target sheet by name as below

Worksheet wsToQuery = lstSheet.Find(a => a.Name.Contains(name));

Hope it helps...

See my answer at: Get all worksheet names in plaintext from Excel with C# Interop?

foreach ( Worksheet worksheet in excelWorkbook.Worksheets )
{
   MessageBox.Show( worksheet.Name );
}

You could use a dictionary:

Dictionary<string, Worksheet> dict = new Dictionary<string, Worksheet>();
foreach ( Worksheet worksheet in excelWorkbook.Worksheets )
{
   dict.Add( worksheet.Name, worksheet );
}
// accessing the desired worksheet in the dictionary
MessageBox.Show( dict[ "Sheet1" ].Name );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM