Search code examples
c#excelexcellibrary

ExcelLibrary Creating Too Many Worksheets


I am trying to write output to an Excel workbook using ExcelLibrary. I want this workbook to contain only one sheet but I can't find any way to either create a workbook with only one sheet or remove the extra sheets after creation. All of the examples I have found do not work.

Any advice is appreciated.

Regards.


Solution

  • The Worksheets are available to you via the Worksheets property, which is simply a generic list of Worksheet objects - i.e. List<Worksheet>.

    You can treat this list like any generic List<T> and use Clear(), Remove(), etc. to manipulate the list of worksheets.

    Workbook workbook = new Workbook();
    workbook.Worksheets.Clear(); // remove all worksheets
    
    Worksheet mySheet = new Worksheet();
    workbook.Worksheets.Add(mySheet); // add a new worksheet
    workbook.Worksheets.Remove(mySheet); // remove a particular worksheet
    workbook.Worksheets.RemoveAt(4); // remove a worksheet at specific index