简体   繁体   中英

C# EPPlus merge Excel Files

I want to merge multiple Excel files with EPPlus in C#.

I did the following:

using (MemoryStream protocolStream = new MemoryStream())
{
    ExcelPackage pck = new ExcelPackage();
    HashSet<string> wsNames = new HashSet<string>();

    foreach (var file in files)
    {
        ExcelPackage copyPck = new ExcelPackage(new FileInfo(file));
        foreach (var ws in copyPck.Workbook.Worksheets)
        {
            string name = ws.Name;
            int i = 1;
            while (!wsNames.Add(ws.Name))
                name = ws.Name + i++;
            ws.Name = name;
            var copiedws = pck.Workbook.Worksheets.Add(name);
            copiedws.WorksheetXml.LoadXml(ws.WorksheetXml.DocumentElement.OuterXml);
        }
    }
    pck.SaveAs(protocolStream);
    protocolStream.Position = 0;
    using (FileStream fs = new FileStream(resultFile, FileMode.Create))
        protocolStream.CopyTo(fs);
}

But I get the following error in pck.SaveAs(protocolStream) :

System.ArgumentOutOfRangeException

in System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) in System.Collections.Generic.List 1.get_Item(Int32 index) in OfficeOpenXml.ExcelStyleCollection 1.get_Item(Int32 PositionID)

I also tried it with the Worksheet.Copy method, but I lose the styling with it.

Here is an example of merging several files into one by coping all worksheets from source excel files.

var files = new string[] { @"P:\second.xlsx", @"P:\second.xlsx" };

        var resultFile = @"P:\result.xlsx";

        ExcelPackage masterPackage = new ExcelPackage(new FileInfo(@"P:\first.xlsx"));
        foreach (var file in files)
        {
            ExcelPackage pckg = new ExcelPackage(new FileInfo(file));

            foreach (var sheet in pckg.Workbook.Worksheets)
            {
                //check name of worksheet, in case that worksheet with same name already exist exception will be thrown by EPPlus

                string workSheetName = sheet.Name;
                foreach (var masterSheet in masterPackage.Workbook.Worksheets)
                {
                    if (sheet.Name == masterSheet.Name)
                    {
                        workSheetName = string.Format("{0}_{1}", workSheetName, DateTime.Now.ToString("yyyyMMddhhssmmm"));
                    }
                }

                //add new sheet
                masterPackage.Workbook.Worksheets.Add(workSheetName, sheet);
            }
        }

        masterPackage.SaveAs(new FileInfo(resultFile));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM