在 C# 中使用 epplus 读取密码保护 excel

Reading password protected excel using epplus in c#

我正在使用 epplus 库下载带密码的 excel 文件。下载部分工作正常。

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

    }
}

但是每当我尝试上传这个受密码保护的文件时,它都会给我以下错误

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

因此,我通过提供读取文件所需的密码解决了上述错误。下面是相同的代码。

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

但是,在提供密码后,由于以下错误

,我仍然无法read/upload excel 文件

The stream must be read/write

所以我的问题是如何使用 Stream 读取受密码保护的文件。我在网络 api.

中使用此代码

感谢任何帮助!

它是 XLS 还是 XLSX 文件? EPplus 无法处理 XLS 文件。

下面是我如何简单地使用 EPPLUS :

using (ExcelPackage xlPackage = new ExcelPackage(new FileInfo(fileName), "password"))
{}

当我尝试上传 excel 文件时,它显示代码错误 "The file is not an valid Package file. If the file is encrypted, please supply the password in the constructor".

但是我的 excel 文件没有加密,也没有密码保护。

我通过使用 try catch 找到了解决方案,就像我刚刚打开我的 excel 文件,然后尝试将该文件从 .xls 格式保存为 .xlsx 格式。

执行此操作后,文件上传成功,EPPlus dll 没有给出任何错误并且运行良好!