Copy excel worksheet

  • VSTO
  • Spire.XLS
  • Download Sample Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;

namespace VSTO
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            //Add a new worksheet
            Excel.Workbook newWorkbook = this.Application.Workbooks.Add();
            Excel.Worksheet worksheet = newWorkbook.ActiveSheet;

            //Set the text of the specified range
            Excel.Range cells = worksheet.Cells;
            cells.set_Item(1, 1, "Spire.XLS");  
  
            //Copy worksheet
            worksheet.Copy(worksheet);

            //Save
            newWorkbook.Save();
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Spire.Xls;

namespace Spire.XLS
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize a new instance of workbook
            Workbook workbook = new Workbook();

            //Add worksheet and set text of specified range
            Worksheet worksheet1 = workbook.Worksheets.Add("Sheet"); ;
            worksheet1.Range[1, 1].Text = "Spire.XLS";

            //add worksheet and name them
            Worksheet worksheet2=workbook.Worksheets.Add("Copied sheet");   
                   
            //copy worksheet to the new added worksheets
            worksheet2.CopyFrom(worksheet1);

            //Save and Launch
            workbook.SaveToFile("CopiedWorksheet.xlsx", ExcelVersion.Version2010);
            System.Diagnostics.Process.Start("CopiedWorksheet.xlsx");

        }
    }
}