M.Beta M.Beta - 1 month ago 43
C# Question

MemoryStream using EPPlus

In this a assembly, i was exporting excel file directly to the local disk but now i am trying to do this in two steps:
first to write it to memorystream , and then save the memory stream to the local disk. Not sure if this is right or not. it does not give me anything whenever i run. thoughts?

public static void Createxlsx(string filename)
{
FileInfo newFile = new FileInfo ("C:\\ConsoleApplicationXLSX\\" + filename + ".xlsx");
MemoryStream stream = new MemoryStream();

//create a package
using (var package = new ExcelPackage(stream))
{
var worksheet = package.Workbook.Worksheets.Add("worksheet");

package.Save();
}
}

Answer
public static void Createxlsx(string filename) 
{
    MemoryStream stream = new MemoryStream();
    //create a package 
    using (var package = new ExcelPackage(stream)) // disposing ExcelPackage also disposes the above MemoryStream
    {
        var worksheet = package.Workbook.Worksheets.Add("worksheet");
        package.Save();

        // see the various ways to create/open a file, Create is just one of them
        // open the file stream
        using(var file = System.IO.File.Open("C:\\ConsoleApplicationXLSX\\" + filename + ".xlsx", System.IO.FileMode.CreateNew))
        {
            stream.Position = 0; // reset the position of the memory stream
            stream.CopyTo(file); // copy the memory stream to the file stream
        }
    }
}

Some notes

  • Wrap your streams (memory, file, etc) in using statements. This will ensure that the stream is always released/freed (using the implemented IDisposable interface) after it is out of scope.
  • See FileMode, the option I chose above CreateNew will throw an exception if you try to overwrite an existing file. If you do not care about that use Create instead.
  • Finally you must reset the position of the stream before you copy it, otherwise it will pick up where the current position left off and usually this is at the end of the stream.

Edit

You could also do this without the MemoryStream.

public static void Createxlsx(string filename) 
{
    using(var file = System.IO.File.Open("C:\\ConsoleApplicationXLSX\\" + filename + ".xlsx", System.IO.FileMode.CreateNew))
    using (var package = new ExcelPackage(file)) // disposing ExcelPackage also disposes the above MemoryStream
    {
        var worksheet = package.Workbook.Worksheets.Add("worksheet");
        package.Save();
    }
}