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

后端 未结 4 1146
渐次进展
渐次进展 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:36
     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.

    0 讨论(0)
  • 2021-01-03 17:39

    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, e.g. pivot table, charts, formulas, etc. Otherwise the data source will disconnect and any changes in one sheet won't effect the other.

    0 讨论(0)
  • 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);
    
                    }
    
    
                }
    
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-03 17:45

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

    0 讨论(0)
提交回复
热议问题