C# EPPlus merge Excel Files

不羁岁月 提交于 2020-05-27 03:05:30

问题


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.List1.get_Item(Int32 index) in OfficeOpenXml.ExcelStyleCollection1.get_Item(Int32 PositionID)

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


回答1:


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


来源:https://stackoverflow.com/questions/36905962/c-sharp-epplus-merge-excel-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!