简体   繁体   中英

How to copy selected sheets from excel file to a new excel file created by program

Hi everyone i have an excel file which i want to use as source for new excel files.I saw some examples that can copy all sheets,however my problem is that i want to copy only selected sheets from the source file and create new file with the selected sheets. eg this would be like if my main table has sheets x,y,z,c,f,g and user selects z,f,gi will only select these three create a new .xlsx file and put them there.Is this possible with c#? thank you in advance

You can copy the selected sheets for example in VBA, The below will create a new workbook with selected sheets

Sheets(Array("Sheet1", "Sheet3", "Sheet4")).Copy

In C#, you can so the same thing as

    private void button1_Click(object sender, EventArgs e)
    {
        Excel.Application xlexcel;
        Excel.Workbook xlWorkBook;
        Excel.Sheets worksheets;

        object misValue = System.Reflection.Missing.Value;

        xlexcel = new Excel.Application();

        xlexcel.Visible = true;

        //~~> Open a File
        xlWorkBook = xlexcel.Workbooks.Open("C:\\Sample.xlsx", 0, true, 5, "", "", true,
        Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

        //~~> Specify the sheets you want to copy
        String[] selectedSheets = { "a", "c", "d" };

        //~~> Set your worksheets
        worksheets = xlWorkBook.Worksheets;

        //~~>Copy it. This will create a new Excel file with selected sheets
        ((Excel.Sheets)worksheets.get_Item(selectedSheets)).Copy();

    }

Screenshot

在此处输入图片说明

yes it is possible in command prompt you can use copy command to copy the files from many excel sheets to single sheet the command is c:/path of the file copy sourcefile destinationfile

thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM