How to merge two Excel workbook into one workbook in C#?

后端 未结 4 1169
渐次进展
渐次进展 2021-01-03 17:04

Let us consider that I have two Excel files (Workbooks) in local. Each Excel workbook is having 3 worksheets.

Lets say WorkBook1 is having Sheet1, Sheet2, Sheet3

4条回答
  •  甜味超标
    2021-01-03 17:45

    Here's a working sample that joins two books into a new one, hope it will give you an idea:

    using System;
    using Excel = Microsoft.Office.Interop.Excel;
    using System.Reflection; 
    
    
    namespace MergeWorkBooks
    {
        class Program
        {
            static void Main(string[] args)
            {
                Excel.Application app = new Excel.Application();
    
                app.Visible = true;
                app.Workbooks.Add("");
                app.Workbooks.Add(@"c:\MyWork\WorkBook1.xls");
                app.Workbooks.Add(@"c:\MyWork\WorkBook2.xls");
    
    
                for (int i = 2; i <= app.Workbooks.Count; i++)
                {
                    int count = app.Workbooks[i].Worksheets.Count;
    
                    app.Workbooks[i].Activate();
                    for (int j=1; j <= count; j++)
                    {
                        Excel._Worksheet ws = (Excel._Worksheet)app.Workbooks[i].Worksheets[j];
                        ws.Select(Type.Missing);
                        ws.Cells.Select();
    
                        Excel.Range sel = (Excel.Range)app.Selection;
                        sel.Copy(Type.Missing);
    
                        Excel._Worksheet sheet = (Excel._Worksheet)app.Workbooks[1].Worksheets.Add(
                            Type.Missing, Type.Missing, Type.Missing, Type.Missing
                            );
    
                        sheet.Paste(Type.Missing, Type.Missing);
    
                    }
    
    
                }
    
            }
        }
    }
    

提交回复
热议问题