首页 > 解决方案 > 在c#中使用epplus读取密码保护的excel

问题描述

我正在使用 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");

    }
}

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

该文件不是有效的包文件。如果文件被加密,请在构造函数中提供密码。

所以,我已经解决了上述错误,我提供了读取文件所需的密码。下面是相同的代码。

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

但是,在提供密码后,由于以下错误,我仍然无法读取/上传 excel 文件

流必须是读/写的

所以我的问题是如何使用 Stream 读取受密码保护的文件。我在 web api 中使用这个代码。

对此的任何帮助表示赞赏!

标签: c#asp.net-web-apiasp.net-core-webapiepplus

解决方案


它是 XLS 还是 XLSX 文件?EPplus 不能处理 XLS 文件。

在这里,我如何简单地使用 EPPLUS :

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

推荐阅读