7
votes

I have an excel workbook with many, many sheets. I want to delete all the sheets except for three of them.

Specifically, i would like to know if there is a way to remove the sheets using sheet name instead of ordinals (sheet number).

I am using excel interop and C# to work with Excel.

Microsoft.Office.Interop.Excel.Application xlApp = null;
Excel.Workbook xlWorkbook = null;
Excel.Sheets xlSheets = null;
Excel.Worksheet xlNewSheet = null;
3

3 Answers

11
votes
xlApp.DisplayAlerts = false;
for (int i = xlApp.ActiveWorkbook.Worksheets.Count; i > 0 ; i--)
{
    Worksheet wkSheet = (Worksheet)xlApp.ActiveWorkbook.Worksheets[i];
    if (wkSheet.Name == "NameOfSheetToDelete")
    {
        wkSheet.Delete();
    }
}
xlApp.DisplayAlerts = true;
2
votes

I know this is old but I just use the fallowing

workBook.Sheets["Sheet1"].Delete();

1
votes

I know this thread is really old but for future visitors, if you know the names of the sheets you want to delete, a better way is to loop over the names of the sheets like this:

Workbook book = excelApp.Workbooks.Open("filePathHere");
string[] sheetsToDelete = {"s1", "s2"};
excelApp.DisplayAlerts = false; 
foreach(string sheetToDelete in sheetsToDelete )
{
    book.Worksheets[sheetToDelete].Delete();
}
excelApp.DisplayAlerts = true;

It's always good practice to avoid deleting items in a collection while iterating through it.