Check if sheet exists in excel

How to check if a sheet exists in excel using interop. I tried the following, but it throws a COMException if not. Is there a better way to find out than looking at the exception.

Worksheet sheet = null; Sheets worksheets = some; sheet = (Worksheet)worksheets.get_Item("sheetName"); if(sheet!=null) { //do something } 

Edit:

Thanks for the input guys.

I wrote a function

 private Dictionary<string, Worksheet> GetSheetsMap(Sheets worksheets) { if (worksheets == null) throw new ArgumentNullException("worksheets"); Dictionary<string, Worksheet> map = new Dictionary<string, Worksheet>(StringComparer.CurrentCultureIgnoreCase); foreach (Worksheet s in worksheets) { map.Add(s.Name, s); } return map; } 

And I use it as below

  Dictionary<string, Worksheet> sheetMap = GetSheetsMap(worksheets); Worksheet sheet = null; if (sheetMap.TryGetValue(ExtendedTemplateManager.BasicUserTemplate, out sheet)) { //found it. } else { // not } 
+4
source share
4 answers

Do you have a Workbook object? If so, you can iterate over the Workbook.Sheets array and check the Name property of each sheet.

 foreach (Sheet sheet in workbook.Sheets) { if (sheet.Name.equals("sheetName")) { //do something } } 
+11
source

First, consider whether the exception does not fit. You expect that there will be a sheet with a specific name. If this is not the case, can you still make sense to continue running your program?

If you can, you can avoid the exception by iterating over the collection of sheets and finding a match in the Name property.

+3
source

Here's the LINQ way for this (and this method returns null if the sheet does not exist):

 workbook.Worksheets.Cast<Worksheet>().FirstOrDefault(worksheet => worksheet.Name == worksheetName); 
+3
source

If you have worksheets and book objects, you can do a parent check

if (sheet.Parent == workbook)

0
source

Source: https://habr.com/ru/post/1308152/


All Articles