How do I merge multiple excel files to a single excel file

旧时模样 提交于 2019-12-02 11:43:38

In your inner loop you add a new worksheet to your 'finalized' workbook ('sheet') AND copy a worksheet before it for every source sheet. So every 'sheet' created by your Add command will be empty as in fact you create two sheets for each source sheet. Another problem is, that - as you mentioned - arrays in excel are 1-based; so you have to loop until j <= count not j < count.

So I think that code would work better:

Excel.Worksheet dummy = finalized.Worksheets[1];

for (int i = 2; i <= excel.Workbooks.Count; i++)
{
    int count = excel.Workbooks[i].Worksheets.Count;

    for (int j = 1; j <= count; j++)
    {
        Excel._Worksheet pastee = (Excel._Worksheet)excel.Workbooks[i].Worksheets[j];
        pastee.Copy(dummy);
    }
}

dummy.Delete();

The simplest way to merge worksheets into one is through a third part component called Spire.Xls. It’s a standalone .NET component.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Xls;
using System.Data;


namespace Spire.XLS
{
    class Program
    {
        static void Main(string[] args)
    {

        Workbook workbook = new Workbook();
        //load the first workbook
        workbook.LoadFromFile(@"merge1.xlsx");
        //load the second workbook
        Workbook workbook2 = new Workbook();
        workbook2.LoadFromFile(@"merge2.xlsx");

        //import the second workbook's worksheet into the first workbook using a datatable
        Worksheet sheet2 = workbook2.Worksheets[0];
        DataTable dataTable = sheet2.ExportDataTable();
        Worksheet sheet1 = workbook.Worksheets[0];
        sheet1.InsertDataTable(dataTable, false, sheet1.LastRow + 1, 1);


        //save the workbook
        workbook.SaveToFile("result.xlsx");
    }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!