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();
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With