【发布时间】:2018-10-22 12:59:16
【问题描述】:
我正在使用 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 中使用此代码。
对此的任何帮助表示赞赏!
【问题讨论】:
-
我不是专家,但是 'var stream = fileObject.OpenreadStream()' 就像它说的那样,打开一个只读流,其中作为 'new ExcelPackage(Stream, "password" );'想要一个读/写流。你能把它改成'var stream = fileObject.OpenStream()'吗?我不确定它是什么类型,但也许它拥有类似的方法。
-
@DubDub 不,只有一种方法可以读取文件,没有其他方法可用
-
fileObject的类型是什么?
-
如果您保存了文件,则可以使用以下答案建议的方法。如果你不能,那么你会想要使用 fileObject.CopyTo() 方法,它会将该文件的内容复制到一个流中。看看这里:docs.microsoft.com/en-us/dotnet/api/…我可能会建议尝试一个几个不同的,内存流可能是您想要采用的方法,因此创建一个本地 MemorySteam,然后调用 fileObject.CopyTo(MemoryStream),然后尝试使用该流创建 Excel 包。
-
@DubDub 感谢您的解决方案.. 成功了!
标签: c# asp.net-web-api asp.net-core-webapi epplus