如何将两个Excel文件及其工作表名称合并为一个? [英] How to merge two excel files into one with their sheet names?

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

问题描述

对于两个Excel工作表的合并,我使用下面的代码.

For merging of two excel sheet, I am using below code.

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工作表.

This code is working good for me for merging excel workbook. But at the time of merging I am not getting the excel sheet names. Here I need that when the excel is merging at the same time the sheet names should also go to the merged excel sheet.

推荐答案

以下内容对我来说很好,包括复制名称和名称冲突之处,甚至可以处理Sheet1(2)等.

The following worked fine for me, including copying the name and where the name clashed it kindly even handled the Sheet1(2) etc.

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

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

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