【问题标题】:How to password protect an excel generated from a byte[]?如何密码保护从字节[]生成的excel?
【发布时间】:2019-03-08 05:37:47
【问题描述】:

我有数据必须加载到字节数组中的 excel 文件中,我需要对其应用密码保护。 我尝试将 byte[] 转换为数据表/列表,并尝试使用 Excelpackage 应用密码保护,但我无法将 byte[] 数组中的数据正确转换为任何形式。我的文件正在下载,但有一些奇怪的数据。有人可以分享你的知识吗?

            response.Clear();
            response.Buffer = true;
            response.ContentEncoding = System.Text.Encoding.UTF8;
            response.ContentType = mimeType; 
            response.AddHeader("content-disposition", "attachment;filename=" 
            + Uri.EscapeDataString(fileName));
            response.Charset = "";
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            DataTable dt;
            MemoryStream stream;
            using (stream = new MemoryStream(fileBytes))
            {

               BinaryFormatter bin = new BinaryFormatter();
               stream.Seek(0, SeekOrigin.Begin);
               dt = (DataTable)formatter.Deserialize(stream);
               stream.Close();
            }
            using (ExcelPackage pack = new ExcelPackage())
            {

                ExcelWorksheet ws = pack.Workbook.Worksheets.Add("heelo");
                ws.Cells["A1"].LoadFromDataTable(dt, true);
                pack.Save("123");
                var ms = new System.IO.MemoryStream();
                pack.SaveAs(ms);
                ms.WriteTo(HttpContext.Current.Response.OutputStream);
                ms.Close();

            }
            response.Flush();
            response.End();

【问题讨论】:

  • @SirRufo 我的意思是是的,但就像它是依赖于至少几个库和一些强命名字段的程序的子集。也许会详细说明
  • 您能按照您的建议编辑代码吗?

标签: c# epplus password-protection excelpackage


【解决方案1】:

在跟踪您的代码时遇到了一些麻烦。为什么response mime 键入 PDF?我想你会希望这样

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

response 实际上是否与 MemoryStreams 有任何关系,因为我没有看到两者之间的引用?

无论如何,如果您有可用的ExcelPackage,并且想使用密码写信给Stream,您可以调用重载:

pack.SaveAs(ms, "MyPassword")

这里有更多信息:Password Protected Excel Download using EPPLUS

【讨论】:

  • 我已经尝试过了,但还是不行。我认为问题出在从 byte[] 转换为 datatable 生成的数据上(实际上“dt”没有保存有意义的数据)。如果我使用“Binary Writer”直接在 Excel 文件中下载 byte[] 而没有密码保护,生成的数据格式正确。
  • @Aparna 它仍然不完全清楚fileBytes 的来源。如果它是带有密码的保存的 excel 文件,您能否使用其他重载之一,例如 public ExcelPackage(FileInfo newFile, string password) 或 @987654332 @?你可以在这里看到它们:github.com/JanKallman/EPPlus/blob/master/EPPlus/…
  • 这里的filebytes(从SSRS报告生成)包含要转储到正在生成的excel文件中的数据。它不是保存文件,但我们必须从字节数组(命名为filebytes ) 带有密码保护。我已经尝试过您的建议,但在我的情况下不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-27
  • 2016-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
相关资源
最近更新 更多