Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the Worksheet already exist in Interop

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();
like image 512
Anand S Avatar asked Feb 22 '13 09:02

Anand S


2 Answers

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...

like image 184
Charles HETIER Avatar answered Oct 04 '22 22:10

Charles HETIER


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.

like image 42
John Willemse Avatar answered Oct 04 '22 22:10

John Willemse