Work on a MemoryStream instead of a File

Topics: Developer Forum
Nov 16, 2010 at 1:42 PM

We want to use ExcelPackage in a ASP.NET application to generate an Excel file on the fly and then save it to the ResponseStream.

I couldn't find a way to use SaveAs(Stream s) or to create anew ExcelPackage using new ExcelPackage(Stream s), that would make it that much more versatile!

Dec 8, 2010 at 3:52 PM

Hi, I have the same problem but was easy to make that implementation....

[ExcelPackage.cs]

        private MemoryStream _memoryStream = null;
        private Stream _outputStream = null;

        public ExcelPackage(Stream outputStream, FileInfo template) {
            _outputStream = outputStream;
            if (template.Exists) {
                _memoryStream = new MemoryStream();
                var templateStream = template.OpenRead();
                var bytes = new byte[1024]; var bytesRead = 0;
                while ((bytesRead = templateStream.Read(bytes, 0, bytes.Length)) != 0) {
                    _memoryStream.Write(bytes, 0, bytesRead);
                }

                _package = Package.Open(_memoryStream, FileMode.Open, FileAccess.ReadWrite);
            } else
                throw new Exception("ExcelPackage Error: Passed invalid TemplatePath to Excel Template");
        }

        public void Save() {
            Workbook.Save();

            if (_memoryStream != null && _outputStream != null) {
                _memoryStream.Position = 0; _memoryStream.Flush();
                var bytes = new byte[1024]; var bytesRead = 0;
                while ((bytesRead = _memoryStream.Read(bytes, 0, bytes.Length)) != 0) _outputStream.Write(bytes, 0, bytesRead);
            }
        }
Apr 17, 2013 at 5:38 PM
Nice job. Thanks.