5

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();

3 Answers 3

15

This extension method returns the worksheet if it exists, null otherwise:

public static class WorkbookExtensions
{
    public static Excel.Worksheet GetWorksheetByName(this Excel.Workbook workbook, string name)
    {
        return workbook.Worksheets.OfType<Excel.Worksheet>().FirstOrDefault(ws => ws.Name == name);
    }
}

The linq method .Any() can be used instead of FirstOrDefault to check whether the worksheet exists as well...

1
  • 2
    just I used ws.Name.Equals(...) method in lamda expression to allow comparison with ignore case.
    – Asereware
    Oct 1, 2016 at 2:47
13

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.

2
  • HI , Thank u If possible can you tell me how to select the existing sheet so the sheet can worked on with
    – Anand S
    Feb 22, 2013 at 11:06
  • 7
    Thank u it solved my issue :) , the second method throws an exception
    – Anand S
    Feb 22, 2013 at 13:29
5

Why not just do this:

try {

    Excel.Worksheet wks = wkb.Worksheets["Example"];

 } catch (System.Runtime.InteropServices.COMException) {

    // Create the worksheet
 }

 wks.Select();

The other way avoids throwing and catching exceptions, and certainly it's a legitimate answer, but I found this and wanted to put this up as an alternative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.