Merging cells means joining two or more separate cells into one large cell, which is useful when you need to create a label that spans multiple columns. In this article, we will demonstrate how to merge or unmerge cells in Excel in C# and VB.NET using Spire.XLS for .NET library.
Install Spire.XLS for .NET
To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.XLS
Merge Cells in Excel in C# and VB.NET
The following are the steps to merge cells in Excel:
- Create a Workbook instance
- Load the Excel file using Workbook.LoadFromFile() method.
- Get the desired worksheet using Workbook.Worksheets[sheetIndex] property.
- Access the specific range of cells and merge them into one using XlsRange.Merge() method.
- Center the text in the merged cell by setting CellRange.Style.HorizontalAlignment property to HorizontalAlignType.Center.
- Save the result file using Workbook.SaveToFile() method.
- C#
- VB.NET
using Spire.Xls; namespace MergeCells { class Program { static void Main(string[] args) { //Create a Workbook instance Workbook workbook = new Workbook(); //Load the Excel file workbook.LoadFromFile("Sample.xlsx"); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Merge cells A1-D1 into one cell CellRange range = sheet.Range["A1:D1"]; range.Merge(); //Center the text in the merged cell range.Style.HorizontalAlignment = HorizontalAlignType.Center; //Save the result file workbook.SaveToFile("MergeCells.xlsx", ExcelVersion.Version2013); } } }
Unmerge Cells in Excel in C# and VB.NET
The following are the steps to unmerge cells in Excel:
- Create a Workbook instance
- Load the Excel file using Workbook.LoadFromFile() method.
- Get the desired worksheet using Workbook.Worksheets[sheetIndex] property.
- Access the specific range of cells and unmerge them using XlsRange.UnMerge() method.
- Save the result file using Workbook.SaveToFile() method.
- C#
- VB.NET
using Spire.Xls; namespace UnmergeCells { class Program { static void Main(string[] args) { //Create a Workbook instance Workbook workbook = new Workbook(); //Load the Excel file workbook.LoadFromFile("MergeCells.xlsx"); //Get the first worksheet Worksheet sheet = workbook.Worksheets[0]; //Unmerge cells A1-D1 CellRange range = sheet.Range["A1:D1"]; range.UnMerge(); //Save the result file workbook.SaveToFile("UnMergeCells.xlsx", ExcelVersion.Version2013); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.