简体   繁体   中英

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

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

Workbook2 is having Sheet1, Sheet2, Sheet3.

So here I need to merge these two excel workbook into one and the new excel workbook that is let's say Workbook3 which will have total 6 worksheets (combination of workbook1 and workbook2).

I need the code that how to perform this operation in c# without using any third party tool. If the third party tool is free version then its fine.

An easier solution is to copy the worksheets themselves , and not their cells.

This method takes any number of excel file paths and copy them into a new file:

private static void MergeWorkbooks(string destinationFilePath, params string[] sourceFilePaths)
{
  var app = new Application();
  app.DisplayAlerts = false; // No prompt when overriding

  // Create a new workbook (index=1) and open source workbooks (index=2,3,...)
  Workbook destinationWb = app.Workbooks.Add();
  foreach (var sourceFilePath in sourceFilePaths)
  {
    app.Workbooks.Add(sourceFilePath);
  }

  // Copy all worksheets
  Worksheet after = destinationWb.Worksheets[1];
  for (int wbIndex = app.Workbooks.Count; wbIndex >= 2; wbIndex--)
  {
    Workbook wb = app.Workbooks[wbIndex];
    for (int wsIndex = wb.Worksheets.Count; wsIndex >= 1; wsIndex--)
    {
      Worksheet ws = wb.Worksheets[wsIndex];
      ws.Copy(After: after);
    }
  }

  // Close source documents before saving destination. Otherwise, save will fail
  for (int wbIndex = 2; wbIndex <= app.Workbooks.Count; wbIndex++)
  {
    Workbook wb = app.Workbooks[wbIndex];
    wb.Close();
  }

  // Delete default worksheet
  after.Delete();

  // Save new workbook
  destinationWb.SaveAs(destinationFilePath);
  destinationWb.Close();

  app.Quit();
}

Edit: notice that you might want to Move method instead of Copy in case you have dependencies between the sheets, eg pivot table, charts, formulas, etc. Otherwise the data source will disconnect and any changes in one sheet won't effect the other.

There are generally two ways to automate Excel tasks with C#.

  1. Use the Microsoft.Office.Interops library
  2. Use a third-party library

Why would you ever go for a third party library when Microsoft offers its own library? I am glad you asked.

  • Firstly, the Microsoft.Office.Interop library is terrible to work with as a developer. Documentation sucks & the object model is complex. Have a look at this example
  • Secondly, the library interacts with Excel directly. ie it opens an instance of Excel & then does the work. This means, you will need to have Excel installed on the relevant computer (not always an issue). Additionally, it results in some crippling performance issues - especially in cases where you are working with large datasets or multiple files.

That is why there is a plethora of third party libraries available. Both paid and open-source. I generally dislike paying for stuff & have found the open-source, free ExcelMapper (for very simple scenarios) and EPPlus libraries really great to work with.

How to merge two Excel workbooks using EPPlus Here is the code:

 var file1 = new FileInfo(@"C:\Temp\Sample\Book 1.xlsx");
 var file2 = new FileInfo(@"C:\Temp\Sample\Book 2.xlsx");
 var mergedFileName = new FileInfo(@"C:\Temp\Sample\Merged.xlsx");

 //lets open the file
 using (var firstFile = new ExcelPackage(file1))
 {
      using (var secondFile = new ExcelPackage(file2))
      {
           foreach (var ws in secondFile.Workbook.Worksheets)
           {
               string worksheetName = ws.Name;
               // if worksheet name already exists - change name
               if (firstFile.Workbook.Worksheets.Any(ar => ar.Name == ws.Name))
                   worksheetName = string.Format("{0} - {1}", worksheetName, "Copy");

                firstFile.Workbook.Worksheets.Add(worksheetName, ws);
            }
       }

       firstFile.SaveAs(mergedFileName);
 }

This is what it looks like when running the code: 在此处输入图片说明 (source: excel-automation-guide.com )

You're looking for Office Autmation libraries in C#.
Here is a sample code to help you get started.

 System.Data.Odbc.OdbcDataAdapter Odbcda;

//CSV File
strConnString = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + SourceLocation + ";Extensions=asc,csv,tab,txt;Persist Security Info=False";

sqlSelect = "select * from [" + filename + "]";

System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection(strConnString.Trim());

conn.Open();
Odbcda = new System.Data.Odbc.OdbcDataAdapter(sqlSelect, conn);
Odbcda.Fill(ds, DataTable);
conn.Close();
  • This would read the contents of an excel file into a dataset.
  • Create multiple datasets like this and then do a merge.

Code taken directly from here .

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);

                }


            }

        }
    }
}

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