How to merge cells with formatting in .NET Excel Library

16 Aug 20262 minutes to read

To merge cells in Excel while preserving only the top-left cell’s value and extending its formatting across the entire merged range, you can use the Range.Merge(true) method. This approach ensures that all other cells within the selected region are cleared, while the content and style of the top-left cell are retained and applied uniformly to the merged area.

The following code examples shows how to merge cells preserving cell value and formatting using C# (cross-platform and Windows-specific) and VB.NET.

using (ExcelEngine excelEngine = new ExcelEngine())
{
    IApplication application = excelEngine.Excel;
    application.DefaultVersion = ExcelVersion.Xlsx;
    IWorkbook workbook = application.Workbooks.Open(Path.GetFullPath(@"Data/InputTemplate.xlsx"));
    IWorksheet worksheet = workbook.Worksheets[0];

    // Merge: true preserves top-left value and copies top-left formatting to merged area
    worksheet.Range["B8:C11"].Merge();

    workbook.SaveAs(Path.GetFullPath(@"Output/Output.xlsx"));
}
using (ExcelEngine excelEngine = new ExcelEngine())
{
    IApplication application = excelEngine.Excel;
    application.DefaultVersion = ExcelVersion.Xlsx;
    IWorkbook workbook = application.Workbooks.Open(InputTemplate.xlsx");
    IWorksheet worksheet = workbook.Worksheets[0];

    // Merge the range and keep top-left value & formatting
    worksheet.Range["B8:C11"].Merge(true);

    workbook.SaveAs("Output.xlsx");
}
Using excelEngine As New ExcelEngine()
    Dim application As IApplication = excelEngine.Excel
    application.DefaultVersion = ExcelVersion.Xlsx
    Dim workbook As IWorkbook = application.Workbooks.Open("InputTemplate.xlsx")
    Dim worksheet As IWorksheet = workbook.Worksheets(0)

    ' Merge the range and keep top-left value & formatting
    worksheet.Range("B8:C11").Merge(True)

    workbook.SaveAs("Output.xlsx")
End Using

A complete working example in C# is present on this GitHub page.