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

后端 未结 3 707
攒了一身酷
攒了一身酷 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:33

    I would like to give an answer for this question, even that it's more than a year since it was asked. I had the same problem myself with a project I'm developing, and it took me a while to find the answer. I will post using VB.NET code instead of C# since I'm not familiar with the last.

    Here is the deal, in order to copy sheets between Excel workbooks it is absolutely necessary to use only ONE Excel Application object and then open both workbooks with that single application, then we can use the known Worksheet.Copy method and simply specify that the sheet is copied after or before the sheet in that other workbook.

    Private Sub ThisWorkbook_Startup() Handles Me.Startup
        Me.Application.Workbooks.Open(filePath)
        Me.Application.Workbooks(2).Worksheets("Reporte"). _
              Copy(After:=Me.Application.Workbooks(1).Worksheets("Hoja1"))
        Me.Application.Workbooks(2).Close()
        Me.Application.DisplayAlerts = False
        Globals.Hoja1.Delete()
        Me.Application.DisplayAlerts = True
    End Sub
    

    In this case the Excel application I'm using is the one that runs my Excel Workbook project, but this would also work:

    Dim xlApp As New Excel.Application
    Dim book1 As Excel.Workbook
    Dim book2 As Excel.Workbook
    book1 = xlApp.Workbooks.Open(filePath1)
    book2 = xlApp.Workbooks.Open(filePath2)
    
    book1.Worksheets("Sheet to be copied").Copy(After:=book2.Worksheets(1))
    

    Of course, the Excel Application will show both workbooks, so after you're finished copying you should close the source Workbook if your intention is not to display it (or at least not long enough for the user to do anything).

    xlApp.Workbooks(1).Close()
    

    This is the way I could do it, the user will see a blinking new Workbook poping up and then closing, which is not really neat, but so far I have no idea how else to do it (or do this copying process in a not-visible way)

    I hope this still has some value. Best regards.

提交回复
热议问题