Search code examples
c#excelvstocom-interopworksheet

Add new Worksheet c# (doubts)


I'm working with C# and Excel for the first time ... And I would like to know how can I add a new worksheet in a Workbook. I have been reading some posts but none works for me so I'm going to post my code.

Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbooks.Add();
Microsoft.Office.Interop.Excel._Worksheet Worksheet = Excel.ActiveSheet;

And with this code I am working with my only Sheet, but now I want to add another one with MMPP name but I can't ... After this I would like to make a dynamic table in the Worksheet MMPP. Can you help me a little?

Thank you for read and try to help!


Solution

  • You'll want to understand the object model. At a high level, it goes like this:

    • Application
      • Workbooks
        • Workbook
          • Sheets
            • Worksheet
              • Range

    A Workbook object has two properties that expose a Sheets object: Sheets and Worksheets - the Sheets collection holds many types of sheets (Chart sheets, for example); if you want to be sure to get a Worksheet object, use the Worksheets collection.

    To create a new worksheet, invoke the Add method of the Worksheets collection:

    using Microsoft.Office.Interop.Excel;
    
    var app = new Application;
    var books = app.Workbooks; // grab a reference to the collection object; you'll want to clean it up later
    var wb = books.Add();
    var sheets = wb.Worksheets; // grab a reference to the collection object: you'll want to clean it up later
    var sheet = sheets.Add();
    

    Adding a worksheet will make that sheet the ActiveSheet, but you don't need to care for that - use your sheet object/variable to manipulate the new sheet.

    The ListObjects property of your sheet is a collection of all named tables on the sheet, so similarly, you'd invoke sheet.ListObjects.Add to create a new ListObject on that sheet. Refer to the documentation, it's full of examples.