Search code examples
c#excelinteropexport-to-excel

I want to add only one sheet after creating an Excel workbook through C#


The code is this

        Excel.Application appC = new Excel.Application();  
        appC.Visible = true;              
        Excel.Workbook bookC = appC.Workbooks.Add(1);  
        Excel.Worksheet sheetC = bookC.Worksheets.Add();  
        sheetC.Name = "something";

The command Workbook.Add() takes one parameter that is supposed to determine how many sheets will be created in the workbook... right?

So why do I get 2 sheets... one named "something" and one named "sheet 2"? What am I doing wrong??


Solution

  • This is the code to create an Excel application object and open a workbook with only ONE sheet and name it as you wish:

    Excel.Application appC = new Excel.Application();    
    appC.SheetsInNewWorkbook = 1;       
    appC.Visible = true;     
    Excel.Workbook bookC = appC.Workbooks.Add();    
    Excel.Worksheet sheetC = appC.Sheets.get_Item(1);   
    sheetC.Name = "name-of-sheet";