How to copy selected sheets from excel file to a n

2019-08-03 02:47发布

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. e.g. this would be like if my main table has sheets x,y,z,c,f,g and user selects z,f,g i will only select these three create a new .xlsx file and put them there.Is this possible with c#? thank you in advance

标签: c# .net excel
2条回答
仙女界的扛把子
2楼-- · 2019-08-03 03:33

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

enter image description here

查看更多
祖国的老花朵
3楼-- · 2019-08-03 03:45

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

查看更多
登录 后发表回答