Skip to content

ArgumentException when inserting columns twice in succession #2291

@swmal

Description

@swmal

EPPlus Version: 8.4.2
OS: Windows 11 Pro 25H2
Execution Environment: Desktop application


Full Error Message

System.ArgumentException: Destination array was not long enough. Check the destination index, length, and the array's lower bounds. (Parameter 'destinationArray')
  at System.Array.CopyImpl(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable)
  at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length)
  at OfficeOpenXml.Core.ChangeableDictionary`1.InsertAndShift(Int32 fromPosition, Int32 add)
  at OfficeOpenXml.ExcelWorksheet.InsertColumn(Int32 columnFrom, Int32 columns, Int32 copyStylesFromColumn)
  at OfficeOpenXml.ExcelWorksheet.InsertColumn(Int32 columnFrom, Int32 columns)
  at EPPlusAddColumnSample.Form1.InsertColumn(String columnName, ExcelWorksheet sheet, Dictionary`2& headerDic, Int32 index) in C:\Users\katao\source\repos\EPPlusAddColumnSample\EPPlusAddColumnSample\Form1.cs:line 75
  at EPPlusAddColumnSample.Form1.AddColumn() in C:\Users\katao\source\repos\EPPlusAddColumnSample\EPPlusAddColumnSample\Form1.cs:line 203

Reproduction Code

public void AddColumn2Times()
{
    var fileInfo = new FileInfo("sample.xlsx");

    try
    {
        using (var package = new ExcelPackage(fileInfo))
        {
            package.Workbook.Calculate();

            var sheet = package.Workbook.Worksheets["Sheet1"];

            InsertColumn("c_1", sheet, 3);
            InsertColumn("d_1", sheet, 5);

            package.SaveAs(fileInfo);
        }
    }
    catch (Exception ex)
    {
        System.IO.File.WriteAllText("error_log.txt", ex.ToString());
        MessageBox.Show(ex.Message);
        return;
    }
}

public void InsertColumn(string columnName, ExcelWorksheet sheet, int index)
{
    sheet.InsertColumn(index, 1);
    sheet.Cells[1, index].Value = columnName;
}

Frequency of Occurrence

Low.

Impact

Occurs only under specific conditions.
Manually adding the column is a functional workaround, so the impact is low.


Specific Conditions

  • It is unclear under which conditions the issue occurs.
  • When the same logic is executed on a newly created XLSX file (created by copying & pasting all sheets into a new workbook), the error does not occur.

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

Projects

Status

PR Backlog

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions