Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return a stream rather than writing to disk?

Tags:

c#

openxml-sdk

I am using OpenXML SDK.

The OpenXML SDK creates a method called CreatePackage as such:

public void CreatePackage(string filePath)
{
    using (SpreadsheetDocument package = SpreadsheetDocument.Create(filePath,               SpreadsheetDocumentType.Workbook))
    {
        CreateParts(package);
    }
}

I call it from my program as follows which will create the Excel file to a given path:

gc.CreatePackage(excelFilePath);
Process.Start(_excelFilePath);

I am not sure how to tweak the code such that it gives back a Stream which shows the Excel file vs having it create the file on disk.

like image 917
Nate Pet Avatar asked Nov 04 '22 08:11

Nate Pet


1 Answers

According to the documentation for SpreadsheetDocument.Create there are multiple overloads, one of which takes a Stream.

so change your code to:

public void CreatePackage(Stream stream)
{
    using (SpreadsheetDocument package = SpreadsheetDocument.Create(stream,               SpreadsheetDocumentType.Workbook))
    {
        CreateParts(package);
    }
}

And then call it with any valid Stream, for example:

using(var memoryStream = new MemoryStream())
{
   CreatePackage(memoryStream);
   // do something with memoryStream
}
like image 112
Jamiec Avatar answered Nov 14 '22 01:11

Jamiec