简体   繁体   中英

EPPlus Excel File Not Working with Password

I am creating an Excel file with my MVC application. Depending on a configuration setting, the file will generate requiring a password or without. I can get the file to generate perfect without. But if I implement a password, I get this error:

Excel cannot open the file '' because the file format is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

Any help would be appreciated. Here is my code:

private void ViewExcelPackageFile(Dataset dtList, string filename)
{
    // 
    var contenttype = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

    // generate password with another function if configuration requires a password

    Response.Clear();
    Response.ContentType = contenttype;
    Response.AddHeader("content-disposition", "attachment;filename=" + filename);

    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    using (var stream = new MemoryStream())
    {
        using (ExcelPackage package = new ExcelPackage())
        {
            var workbook = package.Workbook;
            foreach (var data in dtList)
            {
                ExcelWorksheet ws = workbook.Worksheets.Add(data.TableName.Replace('/', ' '));
                ws.Cells["A1"].LoadFromDataTable(data, true);
            }


            if (password.Length > 0)
            {
                package.SaveAs(stream, password);
            }
            else
            {
                package.SaveAs(stream);
            }

            Response.BinaryWrite(stream.ToArray());
            Response.Flush();
            Response.End();
        }
    }
}

Please correct anything I'm doing wrong, but again, if I don't apply a password, it works fine. TIA!

Try the following

if (!string.IsNullOrEmpty(password))
{
    package.Encryption.Password = password;
}

And then instead of using a MemoryStream, get the bytes directly.

Response.BinaryWrite(package.GetAsByteArray());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM