C# - How to copy a single Excel worksheet from one workbook to another?

后端 未结 3 703
攒了一身酷
攒了一身酷 2020-11-29 12:06

I have a need to copy a worksheet from one workbook into another and I\'m a bit stuck. The premise is that I have a \"master\" workbook that stores the templates for a numb

3条回答
  •  攒了一身酷
    2020-11-29 12:53

    I realise this is a somewhat late reply, but I struggled quite a bit with this so I figured I'd post my solution so that it might help somebody else having this issue.

    Having a template sheet you want to fill many times :

        public void test()
        {
    
            Excel.Application excelApp;
    
            string fileTarget = "C:\target.xlsx";
            string fileTemplate = "C:\template.xlsx";
            excelApp = new Excel.Application();
            Excel.Workbook wbTemp, wbTarget;
            Excel.Worksheet sh;
    
            //Create target workbook
            wbTarget = excelApp.Workbooks.Open(fileTemplate);
    
            //Fill target workbook
            //Open the template sheet
            sh = wbTarget.Worksheets["TEMPLATE"];
            //Fill in some data
            sh.Cells[1, 1] = "HELLO WORLD!";
            //Rename sheet
            sh.Name = "1. SHEET";
    
    
            //Save file
            wbTarget.SaveAs(fileTarget);
    
            //Iterate through the rest of the files
            for (int i = 1; i < 3; i++)
            {
                //Open template file in temporary workbook
                wbTemp = excelApp.Workbooks.Open(fileTemplate);
    
                //Fill temporary workbook
                //Open the template sheet
                sh = wbTemp.Worksheets["TEMPLATE"];
                //Fill in some data
                sh.Cells[1, 1] = "HELLO WORLD! FOR THE " + i + ".TH TIME";
                //Rename sheet
                sh.Name = i + ". SHEET";
    
                //Copy sheet to target workbook
                sh.Copy(wbTarget.Worksheets[1]);
                //Close temporary workbook without saving
                wbTemp.Close(false);
            }
    
            //Close and save target workbook
            wbTarget.Close(true);
            //Kill excelapp
            excelApp.Quit();
        }
    

提交回复
热议问题