How to password protect an excel generated from a byte[]?

823 views Asked by At

I have the data that has to be loaded to an excel file in a byte array and I need to apply password protection on that. I have tried converting byte[] to datatable/list and tried applying password protection using Excelpackage but I am not able to correctly convert data in byte[] array to any form.My file is getting downloaded but with some weired data. Can anyone please share your knowledge?

            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();
1

There are 1 answers

3
Ernie S On

Having a little trouble following you code. Why is response mime type a PDF? I think you would want that to be

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Does response actually have anything to do with the MemoryStreams since I see no reference from one to the other?

In any event, if you have the ExcelPackage available and you want to write to a Stream with a password, you can just call the overload:

pack.SaveAs(ms, "MyPassword")

Here is some more info: Password Protected Excel Download using EPPLUS