Automate Excel with C#
Back to all C# Recipes

How to merge multiple COLUMNS in an Excel File using C#

Introduction

This C# recipe shows how you can use merge multiple columns in an Excel file using the EPPlus library

Ingredients

The recipe uses the EPPlus library version 4.5.3.3. This is the last version of EPPlus under the LGPL License (aka free for commercial uses). You can install it using Nuget Package manager:

Install-Package EPPlus -Version 4.5.3.3

C# Code

var path = @"C:\Temp\ExcelRecipes\Merging\";
var fileName = "MergingColumns.xlsx";

// open excel file using EPPlus
using (ExcelPackage excelFile = new ExcelPackage(new FileInfo(path + fileName)))
{

    // select first worksheet
    var sheet = excelFile.Workbook.Worksheets.First();

    // merge columns in range A1 to D1
    sheet.Cells["A1:D1"].Merge = true;

     // save as a new file
    excelFile.SaveAs(new FileInfo(path + "newFileName.xlsx"));
}

Related C# Recipes

How to merge two Excel Files into a single Excel file

This C# recipe shows how you can merge two Excel files into one Excel file

How to merge multiple Excel Files into a single Excel file

This C# recipe shows how you can use merge multiple Excel files within a directory into a single Excel file