Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete excel worksheets programmatically

Tags:

c#

.net

excel

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;
like image 925
user1144596 Avatar asked May 02 '13 01:05

user1144596


1 Answers

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;
like image 172
Jeremy Thompson Avatar answered Sep 22 '22 05:09

Jeremy Thompson