How do i check if a sheet exists in a excel using interop. I tried the following but it throws an COMException if not there.. Is there a better way of finding out than actually 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
}