How to check if the Worksheet already exist in Interop

c#, excel, excel-interop

Solution

Create a loop like this:

// Keeping track
bool found = false;
// Loop through all worksheets in the workbook
foreach(Excel.Worksheet sheet in wb.Sheets)
{
    // Check the name of the current sheet
    if (sheet.Name == "Example")
    {
        found = true;
        break; // Exit the loop now
    }
}

if (found)
{
    // Reference it by name
    Worksheet mySheet = wb.Sheets["Example"];
}
else
{
    // Create it
}

I'm not into Office Interop very much, but come to think of it, you could also try the following, much shorter way:

Worksheet mySheet;
mySheet = wb.Sheets["NameImLookingFor"];

if (mySheet == null)
    // Create a new sheet

But I'm not sure if that would simply return `null` without throwing an exception; you would have to try the second method for yourself.

Problem

I want to check if the sheet exists before creating it. ``` using Excel = Microsoft.Office.Interop.Excel; Excel.Application excel = new Excel.Application(); excel.Visible = true; Excel.Workbook wb = excel.Workbooks.Open(@"C:\"Example".xlsx"); Excel.Worksheet sh = wb.Sheets.Add(); int count = wb.Sheets.Count; sh.Name = "Example"; sh.Cells[1, "A"].Value2 = "Example"; sh.Cells[1, "B"].Value2 = "Example" wb.Close(true); excel.Quit(); ```

Original source