locked
C# to Copy Excel Worksheet In Same Workbook RRS feed

  • Question

  • I have a worksheet with formatting on it and header rows etc etc.  How can I copy that worksheet in the same workbook and rename that worksheet (the copy)?

    I tried this, but it was unsuccesful

    Excel_Application.ActiveWorkbook.Worksheets.get_Item(worksheet).Copy((Worksheet)Excel_Application.Worksheets[0]);

    Saturday, July 20, 2013 2:03 PM

Answers

  • Hi IndigoMontoya,

    According to you description, you are trying to copy a worksheet in same Workbook in C#.

    In general, there are 2 ways to copy a worksheet in c#:

    (1) VSTO

    Here is quick a sample about copying a worksheet using VSTO:

    namespace ExcelWorkbook
    {
        partial class ActionsPaneControl : UserControl
        {
            public ActionsPaneControl()
            {
                InitializeComponent();
    
                this.button1.Click += new EventHandler(OnButtonClick);
            }
    
    
            public void OnButtonClick(object sender, EventArgs e)
            {
                Worksheet sheet1 = Globals.ThisWorkbook.Sheets[1];
    
                sheet1.Copy(Type.Missing, sheet1);
    
                var copySheetIndex = sheet1.Index + 1;
    
                Worksheet copySheet = Globals.ThisWorkbook.Sheets.get_Item(copySheetIndex);
    
                copySheet.Name = "Copy Sheet";
            }
        }
    }
    

    (2) OpenXML

    About how to copy a worksheet using OpenXml, please refer the article below:

    How to Copy a Worksheet within a Workbook

    Regards,

    Jeffrey


    Jeffrey Chen
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by IndigoMontoya Thursday, July 25, 2013 1:55 PM
    Monday, July 22, 2013 12:27 PM