如何将两个excel文件合并为一个带有工作表名称的文件?

时间:2011-09-27 11:49:44

标签: c# excel excel-interop

对于两个excel表的合并,我使用下面的代码。

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

                }
            }
        }
    }
}

此代码对于合并excel工作簿非常有用。但在合并时我没有得到excel表名。在这里我需要当excel同时合并时,工作表名称也应该转到合并的Excel工作表。

2 个答案:

答案 0 :(得分:3)

以下对我来说很好,包括复制名称和名称冲突的地方,甚至处理Sheet1(2)等。

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++)
{
    for (int j = 1; j <= app.Workbooks[i].Worksheets.Count;j++ )
    {
        Excel.Worksheet ws = app.Workbooks[i].Worksheets[j];
        ws.Copy(app.Workbooks[1].Worksheets[1]);
    }
}

答案 1 :(得分:0)

无错误并改善答案

将result2.xlsx 文件创建为相同的位置,您可以根据需要找到最终的Excel工作表

 class Program
     {        
      static void Main(string[] args)
        {
        Application app = new Application();
        app.Visible = true;
        Workbook w1 = app.Workbooks.Add(@"D:\MyDownload\result2.xlsx");
        Workbook w2 = app.Workbooks.Add(@"D:\MyDownload\merge1.xlsx");
        Workbook w3 = app.Workbooks.Add(@"D:\MyDownload\merge2.xlsx");
        for (int i = 2; i <= app.Workbooks.Count; i++)
        {
            for (int j = 1; j <= app.Workbooks[i].Worksheets.Count; j++)
            {
                Worksheet ws = (Worksheet)app.Workbooks[i].Worksheets[j];
                ws.Copy(app.Workbooks[1].Worksheets[1]);
            }
        }
        app.Workbooks[1].SaveCopyAs(@"D:\MyDownload\result2.xlsx");
        w1.Close(0);
        w2.Close(0);
        w3.Close(0);
        app.Quit();
    }
}