OpenXML - how to save a table to a stream?
I am getting a .xlsx document from a stream (using SpreadsheetDocument.Open(stream, false)
, then storing it in the Spreadsheetdocument field so that I can maintain the same object later.
I have a save method where I should ideally save a SpreadsheetDocument for a thread. There is document..WorkbookPart.Workbook.Save(stream);
, but it 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 to save the table document to a stream?
source to share
I know this is a little old, but I stumbled upon a question when I had the same problem, so I thought I would update it with the solution I found.
My problem turned out to be that I needed to return the stream position to zero.
stream.Position = 0;
From my experiments, the position of the stream after saving the spreadsheet is the end of the stream. When I output my stream to the web browser, it starts the stream from the current position and runs to the end, not from the beginning. I would guess this is consistent with another API in the framework.
source to share
As per the documentation SpreadsheetDocument.Close
Saves and closes the OpenXml package plus all underlying streams.
Update: Have you tried saving the main thread yourself?
File.WriteAllBytes(filename, stream.ToArray());
source to share