Add new sheet in Excel workbook using C#

Add new sheet in Excel workbook using C#

New Sheet:

In Excel worksheet user can insert new sheet by (+) sign next to current sheet or under Home >> Cells Group>>Insert dropdown choose Insert Sheet command. We can achieve same in Excel through C# in VSTO (Visual Studio Tools for Office).

Prerequisites:

  • Visual Studio 2015 or above having Microsoft Office for Developer Tool installed
  • Create Excel Addin in C# code style
  • Create a ribbon designer and put button

Code Example:

private void btnInsertSheet_Click(object sender, RibbonControlEventArgs e)
{
	//addin new sheet and holding reference
	excel.Worksheet mNeWorksheet = Globals.ThisAddIn.Application.ActiveWorkbook.Sheets.Add();
	//rename newly added sheet
	mNeWorksheet.Name = "My_New_Sheet";
}

Sheets.Add Method: takes four optional parameters as follow:

  1. Before : An object that specifies the sheet before which the new sheet is added.
  2. After : An object that specifies the sheet after which the new sheet is added.
  3. Count : The number of sheets to be added. The default value is the number of selected sheets.
  4. Type : Specifies the sheet type. Can be one of the following XlSheetType constants: xlWorksheet, xlChart, xlExcel4MacroSheet, or xlExcel4IntlMacroSheet. If you are inserting a sheet based on an existing template, specify the path to the template. The default value is xlWorksheet.

Before running the code let’s understand what exactly code is doing here. First line we bind the reference for newly added sheet with help of Add method of Sheets collection and finally in second line we are setting the Name property of worksheet object as “My_New_Sheet“.

Output:

Please leave your valuable comments!!!

Next : How to delete/shift/remove cells in a sheet using C# VSTO

Leave a Reply

Your email address will not be published. Required fields are marked *