botangolan
botangolan

Reputation: 331

OpenXML - how to save spreadsheetdocument to stream?

I am getting an .xlsx document from a stream (using SpreadsheetDocument.Open(stream, false) then storing it into a Spreadsheetdocument field so that I can maintain the same object later.

I have a save method where I should ideally be able to save the SpreadsheetDocument to a stream. There is document..WorkbookPart.Workbook.Save(stream); but that just gives me an empty file, and when I save only the first sheet (using document.WorkbookPart.WorksheetParts.First().Worksheet.Save(stream); the file is a mess and does not contain the relevant information. How do I save a spreadsheetdocument to a stream?

Upvotes: 5

Views: 9515

Answers (2)

Jason Robbins
Jason Robbins

Reputation: 83

I know this is a little old but I stumbled across the question when having the same issue so thought I'd update it with the solution I found.

My issue turned out to be that I need to set the stream position back to zero.

stream.Position = 0;

From my experimentation, the position of the stream once the spreadsheet has been saved is the end of the stream. When I outputted my stream to a web browser, it starts the stream from the current position and runs to the end rather than starting from the start. I would assume this is consistent with other API's in the framework.

Upvotes: 2

christophano
christophano

Reputation: 935

According to the documentation, SpreadsheetDocument.Close Saves and closes the OpenXml package plus all underlying part streams.

Update: Have you tried saving the underlying stream itself?

File.WriteAllBytes(filename, stream.ToArray());

Upvotes: 0

Related Questions