1
Vote

A bug when copying a worksheet (ExcelWorksheet) from one document to another

description

I try to copy a worksheet from one Excel document to another one and encountered a problem.
I found an error in the method 'Worksheets.Add'

Here is the code:
private static byte[] CombineXlses(params byte[][] xlses)

{
    using (var targetFile = new TemporaryFile(xlses[0], ".xlsx"))
    using (var targetXls = new ExcelPackage(new FileInfo(targetFile.AbsolutePath)))
    {
        foreach (var xls in xlses.Skip(1))
            using (var sourceXlsFile = new TemporaryFile(xls, ".xlsx"))
            using (var sourceXls = new ExcelPackage(new FileInfo(sourceXlsFile.AbsolutePath)))
                foreach (var sourceSheet in sourceXls.Workbook.Worksheets)
                    targetXls.Workbook.Worksheets.Add(sourceSheet.Name, sourceSheet);
        return targetXls.GetAsByteArray();
    }
}
Here is the error stack:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
   at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
   at OfficeOpenXml.ExcelStyles.CloneStyle(ExcelStyles style, Int32 styleID, Boolean isNamedStyle, Boolean allwaysAdd)
   at OfficeOpenXml.ExcelWorksheets.CloneCells(ExcelWorksheet Copy, ExcelWorksheet added)
   at OfficeOpenXml.ExcelWorksheets.Add(String Name, ExcelWorksheet Copy)
   at Knopka.Web.Modules.Documents.OutgoingDocumentController.CombineXlses(Byte[][] xlses) in S:\src\statistics\Web\Modules\Documents\OutgoingDocumentController.cs:line 426
Have ideas how to solve this?

Thank you in advance.

comments