8

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();
}
Maximilian Ast
  • 3,369
  • 12
  • 36
  • 47
preeti jain
  • 129
  • 1
  • 2
  • 9

4 Answers4

22

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);
Ernie S
  • 13,902
  • 4
  • 52
  • 79
  • Thanks Ernie!! I have similar problem when write excel using template, My code is ' Byte[] bin = pck.GetAsByteArray(); System.IO.File.WriteAllBytes(fullFilePath, bin);' so how can i add password? – preeti jain Feb 10 '16 at 05:23
  • It's working .but when I open excel from mail then it shows me a warning for the recover file. – Rinku Choudhary Feb 04 '20 at 09:20
  • @rinkuChoudhary WIthout more info it is difficult to say. Post a new question with your code and hopefully people can help. – Ernie S Feb 04 '20 at 13:40
5

It's not documented, but you can do as following:

package.Encryption.Password = "your password here";

Then serve your package with Save() or GetAsByteArray() of your choice

Hunter Tran
  • 13,257
  • 2
  • 14
  • 23
0

If you are saving the excel package into a MemoryStream (for sending as an email attachment) you have to do this:

excelPackage.SaveAs(memoryStream, "pa$$w0rd");
Muhammedh
  • 484
  • 1
  • 11
  • 25
0

package.GetAsByteArray("sometest"); ---> this will protect your excel sheet with password sometest :)

surya
  • 17
  • 5