Automate Excel with C#
Back to all C# Recipes

How to password protect an Excel file in C#

Introduction

This C# recipe shows how you can open an unprotected Excel file and save it as a new password protected Excel file

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 unprotectedFile = @"C:\Temp\ExcelRecipes\Password\unprotected.xlsx";
var protectedFile = @"C:\Temp\ExcelRecipes\Password\protected.xlsx";

// open protected file
using ExcelPackage fileExcelFile = new ExcelPackage(new FileInfo(unprotectedFile), "");
// save as unprotected file
fileExcelFile.SaveAs(new FileInfo(protectedFile), "secret123");

Related C# Recipes

How to unprotect a password protected Excel file in C#

This C# recipe shows how you can unprotect a password protected Excel file and save it a as an unprotected file