且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除Excel工作表编程

更新时间:2023-12-05 19:13:40

  xlApp.DisplayAlerts = FALSE;
对于(INT I = xlApp.ActiveWorkbook.Worksheets.Count; I> 0;我 - )
{
    工作表wkSheet =(表)xlApp.ActiveWorkbook.Worksheets [I]
    如果(wkSheet.Name ==NameOfSheetToDelete)
    {
        wkSheet.Delete();
    }
}
xlApp.DisplayAlerts = TRUE;
 

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.

any code / ideas would be helpful.

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

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;