Automate Excel with C#
Back to all C# Recipes

How to split an Excel file into multiple Excel files in C#

Introduction

This C# recipe shows how you split an Excel file's worksheets into multiple Excel files within a directory

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 singleFile = @"C:\Temp\ExcelRecipes\Splitting\single_file.xlsx";
var saveInPath = @"C:\Temp\ExcelRecipes\Splitting\";
ExcelPackage excelFile = new ExcelPackage(new FileInfo(singleFile));

foreach (var sheet in excelFile.Workbook.Worksheets)
{
    // name the new file as per the sheet name
    string newFileName = sheet.Name + ".xlsx";

    // new excel file
    ExcelPackage newFile = new ExcelPackage(new FileInfo(saveInPath + newFileName));

    // add sheet to new file
    newFile.Workbook.Worksheets.Add(sheet.Name, sheet);
    newFile.Save();
}