How to Ungroup Excel Cells in C#

Group the Excel cells is to tie a range of cells together so that they can be collapsed or expanded. But usually, we also need to ungroup the Excel cells. Consequently, the articles aims at introducing how to ungroup Excel cells in C#, through a professional Excel .NET Component Spire.Xls.

Just as its name implies, ungroup Excel cells is to ungroup a range of cells that were previously grouped. Before ungroup Excel cells, we should complete the preparatory work:

  • Download the Spire.XLS and install it on your machine.
  • Add the Spire.XLS.dll files as reference.
  • Open bin folder and select the three dll files under .NET 4.0.
  • Right click property and select properties in its menu.
  • Set the target framework as .NET 4.
  • Add Spire.XLS as namespace.

Then here comes to the explanation of the code:

Step 1: Create an instance of Spire.XLS.Workbook.

[C#]
Workbook workbook = new Workbook();

Step 2: Load the file base on a specified file path.

[C#]
workbook.LoadFromFile(@"group.xlsx");

Step 3: Get the first worksheet.

[C#]
Worksheet sheet = workbook.Worksheets[0];

Step 4: Ungroup the first 5 row cells.

[C#]
sheet.UngroupByRows(1, 5);

Step 5: Save as the generated file.

[C#]
workbook.SaveToFile(@"result.xlsx", ExcelVersion.Version2010);

Full code:

[C#]
using Spire.Xls;
namespace UngroupCell
{
    class Program
    {

        static void Main(string[] args)
        {

            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"group.xlsx");
            Worksheet sheet = workbook.Worksheets[0];
            sheet.UngroupByRows(1, 5);
            workbook.SaveToFile(@"..\..\result.xlsx", ExcelVersion.Version2010);

        }
    }
}

Please preview the original group effect screenshot:

group excel cells

And the generated ungroup effect screenshot:

ungroup excel cells