简体   繁体   中英

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

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM