How to create Excel file using OpenXML without creating a local file?

You could use the overload of SpreadsheetDocument.Create that takes a Stream and pass it a MemoryStream:

MemoryStream memoryStream = new MemoryStream();
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook);

//add the excel contents...

//reset the position to the start of the stream
memoryStream.Seek(0, SeekOrigin.Begin);

return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

Note that as per this StackOverflow question you don’t need to dispose the Stream as it will be done for you by the FileStreamResult class.

Leave a Comment