简体   繁体   中英

OpenXML PowerTools: is it possible to write an Excel spreadsheet to a .Net MemoryStream?

I'm creating an Excel spreadsheet programmatically with PowerTools.

I installed PowerTools 4.5.3.2 in my C#/ASP.Net Core project with Nuget. The project also uses DocumentFormat.OpenXml v2.9.1.

I can generate the spreadsheet OK.

BUT...

I would like to pass the completed spreadsheet back to the user as a.Net MemoryStream.

I've pored over the PowerTools documentation and sample programs on https://github.com/OfficeDev/Open-Xml-PowerTools .

But for the life of me, I haven't seen any way to have PowerTools give me the generated data as a MemoryStream. Or, for that matter, any way to make PowerTools use a MemoryStream I pass in to it.

Q: Any suggestions?

NOTE

All I want to do is:

  1. My ASP.Net web controller calls a function that generates an.xlsx spreadsheet from scratch.

  2. The function uses OpenXML PowerTools (because that seems the most straightforward way to include a Pivot Table in the.xlsx)

  3. Once the function returns, the controller needs to return the.xlsx back to the web client as an Asp.Net Core FileStreamResult object.

In other words, all I want to do is go from 2 (working) to 3 (that's where I'm stuck). I can't seem to "convert" the successfully created spreadsheet into a MVC FileStreamResult compatible object for the controller to pass back to the caller.

Help!

No, it doesn't appear that OpenXml PowerTools will let you write out to anything but an actual disk file.

So I used a temp file, then converted it to a byte[] array to pass back to the caller:

using (OpenXmlMemoryStreamDocument streamDoc = OpenXmlMemoryStreamDocument.CreateSpreadsheetDocument())
{
    doc = streamDoc.GetSpreadsheetDocument();
    ms = new MemorySpreadsheet();
    ...
    string tmpFile = System.IO.Path.GetTempFileName();
    streamDoc.GetModifiedSmlDocument().SaveAs(tmpFile);
    byte[] fileBytes = System.IO.File.ReadAllBytes(tmpFile);
    return fileBytes;

PS: I never did solve this problem: OpenXML SpreadsheetDocument SaveAs() giving file-in-use error

I ultimately gave up on PowerTools and went back to an all-OpenXml solution.

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