Search code examples
c#asp.net-mvcasp.net-mvc-4epplus

Password Protected Excel Download using EPPLUS


I am exporting data in Excel form using EPPLUS Excel Library. I want that when excel downloaded it will ask for password. I have tried following code.

FileInfo newFile = new FileInfo("sample.xlsx");
using (ExcelPackage package = new ExcelPackage(newFile)
{
    ExcelWorksheet ws = package.Workbook.Worksheets.Add("demo");
    ws.Cells[A1].LoadFromDataTable(dataTable, false);
    package.Workbook.Protection.SetPassword("EPPLUS");
    package.Save();
}

Solution

  • Just need to use the .Save overload with a password as the option:

    package.Save("password");
    

    Response To Comments

    To apply a password if saving via a byte array it is very similar:

    Byte[] bin = pck.GetAsByteArray("password");
    System.IO.File.WriteAllBytes(fullFilePath, bin);