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)) {
source share