Automate Excel with C#
Back to all C# Recipes

How to delete columns in Excel using C#

Introduction

This C# recipe shows how you can use EPPlus library to open an Excel file and delete specific columns

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 Snippet

var path = @"C:\Temp\ExcelRecipes\Deleting\";
var fileName = "DeletingColumns.xlsx";

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

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

    // delete column 5 & 9
    sheet.DeleteColumn(5);
    sheet.DeleteColumn(9);

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