Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading password protected excel using epplus in c#

I am downloading the excel file with password using epplus library. The downloading part is working fine.

public ActionResult DownloadExcel()
{

string sFileName = string.Empty;

using (ExcelPackage package = projectBL.DownloadExcel(ID, id1, id3, id4, id5))
   {
     System.Net.Mime.ContentDisposition cd = new System.Net.Mime.ContentDisposition
        {
            FileName = package.File.Name,
        };

        Response.Headers.Add("Content-Disposition", cd.ToString());

        return File(package.GetAsByteArray("password"), "application/vndopenxmlformats-officedocument.spreadsheetml.sheet");

    }
}

But whenever I am trying to upload this password protected file it is giving me below error

The file is not an valid Package file. If the file is encrypted, please supply the password in the constructor.

So, I have resolved the above error my providing the required password to read the file. Below is the code for the same.

public ActionResult UploadExcel()
{
  if (Request.Form.Files != null && Request.Form.Files.Count > 0)
   {
     var fileObject = Request.Form.Files[0];

     string fileName = ContentDispositionHeaderValue.Parse(fileObject.ContentDisposition).FileName.Trim('"');

     var Stream = fileObject.OpenReadStream();

     ExcelPackage package = new ExcelPackage(Stream,"password");

     projectBL.SaveData(package);

     return Json("Records Saved Succesfully.");
    }
}

However, after providing the password still I am not able to read/upload the excel file due to below error

The stream must be read/write

So my question is how can i read the password protected file using Stream. I am using this code in web api.

Any help on this appreciated !

like image 816
XamDev Avatar asked Dec 06 '25 04:12

XamDev


1 Answers

Is it a XLS or XLSX file? EPplus cannot works with XLS files.

Here how I simply do with EPPLUS :

using (ExcelPackage xlPackage = new ExcelPackage(new FileInfo(fileName), "password"))
{}
like image 114
DanB Avatar answered Dec 08 '25 16:12

DanB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!