preeti jain
preeti jain

Reputation: 129

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();
}

Upvotes: 8

Views: 15622

Answers (4)

surya
surya

Reputation: 17

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

Upvotes: 0

Muhammedh
Muhammedh

Reputation: 504

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");

Upvotes: 0

Hunter Tran
Hunter Tran

Reputation: 15425

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

Upvotes: 6

Ernie S
Ernie S

Reputation: 14270

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);

Upvotes: 22

Related Questions