如何合并两个Excel工作簿到C#一个工作簿? [英] How to merge two excel workbook into one workbook in c#?

查看:417
本文介绍了如何合并两个Excel工作簿到C#一个工作簿?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑,我在当地的两个Excel文件(工作簿)。每一个Excel工作簿是具有3个工作表。

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

比方说WorkBook1是有工作表Sheet1,Sheet2中,工作表Sheet 3

Lets say WorkBook1 is having Sheet1, Sheet2, Sheet3

Workbook2是有工作表Sheet1,Sheet2中,工作表Sheet 3。

Workbook2 is having Sheet1, Sheet2, Sheet3.

所以在这里我需要这两个Excel工作簿合并成一个,并在新的Excel工作簿是让我们说Workbook3这将有总共6个工作表(workbook1和workbook2的组合)。

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

我所需要的代码,如何不使用任何第三方工具执行C#此操作。如果第三方工具是免费的版本,那么它的罚款。

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.

请尝试帮助我。其相当紧迫。提前更多clearification请随时问。

Please try to help me out. Its quite urgent. For more clearification please feel free to ask.

谢谢...

推荐答案

下面是联接两本书到一个新的工作示例,希望它会给你一个想法:

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

                }


            }

        }
    }
}

这篇关于如何合并两个Excel工作簿到C#一个工作簿?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆