Search code examples
c#excelepplus

How to add multiple collapse in same outline using Epplus c#


I need a multiple collapse in same outline level.

 for (var j = 0; j <= 2; j++)
  {
    workSheet.Row(j).OutlineLevel = 1;
    workSheet.Row(j).Collapsed = true;
    workSheet.Row(j+3).OutlineLevel = 1;
    workSheet.Row(j+3).Collapsed = true;
  }

Is it possible to achieve two collapse in same outline. Thanks in Advance:)


Solution

  • I think the only way to do it in Excel (putting Epplus aside for a moment) is to create a gap between the groups. In Epplus, you could do something like:

    [TestMethod]
    public void Row_Multiple_Grouping_Test()
    {
        //https://stackoverflow.com/questions/57925761/how-to-add-multiple-collapse-in-same-outline-using-epplus-c-sharp
    
        //Throw in some data
        var dataTable = new DataTable("tblData");
        dataTable.Columns.AddRange(new[]
        {
            new DataColumn("Header", typeof (string)),
            new DataColumn("Col1", typeof (int)),
            new DataColumn("Col2", typeof (int)),
            new DataColumn("Col3", typeof (object))
        });
    
        for (var i = 0; i < 10; i++)
        {
            var row = dataTable.NewRow();
            row[0] = $"Header {i}";
            row[1] = i; row[2] = i * 10;
            row[3] = Path.GetRandomFileName();
            dataTable.Rows.Add(row);
        }
    
        //Create a test file
        var fi = new FileInfo(@"c:\temp\Row_Multiple_Grouping_Test.xlsx");
        if (fi.Exists)
            fi.Delete();
    
        using (var pck = new ExcelPackage(fi))
        {
            var worksheet = pck.Workbook.Worksheets.Add("Sheet1");
            worksheet.Cells.LoadFromDataTable(dataTable, true);
    
            //Create the grouping
            for (var i = 2; i <= 11; i++)
            {
                worksheet.Row(i).OutlineLevel = 1;
                worksheet.Row(i).Collapsed = true;
            }
    
            //Create a gap - cant shrink or hide it because it hides the collapse button in GUI
            worksheet.InsertRow(7, 1);
    
            pck.Save();
        }
    }
    

    Which gives:

    enter image description here

    Problem is you cannot shrink or hide that row without loosing the Expand/Collapse button. Best you can do is put a header/footer with the groups.