SaveAs MemoryStream leads to unreadable content

Nov 10, 2012 at 2:53 AM
Edited Nov 10, 2012 at 2:55 AM

I am using EPPlus 3.1.2 (added using NuGet).  The following test leads to unreadable content.


        public void CanWriteExcle2007UsingStream()
            string templateFilePath = @"D:\Temp\Template.xlsx";  // just an empty Excel workbook created by Excel 2010
            string filePath = @"D:\Temp\Test.xlsx";

            FileInfo templateFile = new FileInfo(templateFilePath);

            using (ExcelPackage package = new ExcelPackage(templateFile, true))
                ExcelWorksheet worksheet = package.Workbook.Worksheets["Sheet1"];

                worksheet.Cells[3, 2].Value = "Test Using Stream";

                // using MemoryStream
                using (MemoryStream ms = new MemoryStream())

                    Assert.IsTrue(ms.Length > 0);

                    SaveToFile(ms, filePath);

        protected void SaveToFile(MemoryStream ms, string filePath)
            byte[] data = ms.GetBuffer();
            SaveToFile(data, filePath);

        protected void SaveToFile(byte[] data, string filePath)
                using (Stream file = File.OpenWrite(filePath))
                    file.Write(data, 0, data.Length);

My project needs to use MemoryStream so it can be transferred between different layers.  After it's written to Test.xlsx, open it with Excel 2010.  And I got the following error message:

Excel found unreadable content in 'Test.xlsx'.  Do you want to recover the content of this workbook?  If you trust the source of this workbook, click Yes.

Nov 11, 2012 at 6:03 PM

Hi blackpuppy,

This is not an EPPlus issue.

Change ms.GetBuffer() to ms.ToArray(), delete Test.xlsx and rerun your test. GetBuffer() will return the entire buffer including unused bytes. ToArray() returns only the data.



Nov 12, 2012 at 12:33 AM

Hi, Mats,

Ya, that does solve the problem. Thanks a lot!


Best regards!

Zhu Ming