You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Can we save multiple worksheets in the same memory stream?
I am receiving the following exception:
NPOI.OpenXml4Net.Exceptions.OpenXML4NetRuntimeException: Fail to save: an error occurs while saving the package : Must support writing (Parameter 'baseOutputStream')
---> System.ArgumentException: Must support writing (Parameter 'baseOutputStream')
at ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream..ctor(Stream baseOutputStream, Deflater deflater, Int32 bufferSize)
at ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream..ctor(Stream baseOutputStream, Deflater deflater)
at ICSharpCode.SharpZipLib.Zip.ZipOutputStream..ctor(Stream baseOutputStream)
at NPOI.OpenXml4Net.OPC.ZipPackage.SaveImpl(Stream outputStream)
--- End of inner exception stack trace ---
at NPOI.OpenXml4Net.OPC.ZipPackage.SaveImpl(Stream outputStream)
at NPOI.OpenXml4Net.OPC.OPCPackage.Save(Stream outputStream)
at NPOI.POIXMLDocument.Write(Stream stream)
at Ganss.Excel.ExcelMapper.Save[T](Stream stream, IEnumerable`1 objects, String sheetName, Boolean xlsx, Func`3 valueConverter)
Code:
var versions= new List<Version>() { new Version { MyProperty = 1 } };
var portfolios = new List<Portfolio>() { new Portfolio { MyProperty = 1 } };
var mapper = new ExcelMapper();
var stream = new MemoryStream();
mapper.Save(stream, versions, "Versions");
mapper.Save(stream, portfolios, "Portfolios");
var bytes = stream.ToArray();
Try writing to Stream.Null on all calls to Save() except the last one. The internal workbook object will be updated on each call but only the last call to Save() will actually write the whole workbook to the target stream.
Nice, it worked! Thanks for the help!
I would like to implement a method AddSheet(IEnumerable objects, string sheetName) that does the same, just to be easier to use, do you agree with that @mganss?
@bh-schmidt Generally, yes. But I wouldn't use the Stream.Null hack but rather refactor the core Save() method to not call Workbook.Write() at the end:
Activity
mganss commentedon Aug 17, 2022
Try writing to
Stream.Nullon all calls toSave()except the last one. The internal workbook object will be updated on each call but only the last call toSave()will actually write the whole workbook to the target stream.bh-schmidt commentedon Aug 17, 2022
Nice, it worked! Thanks for the help!
I would like to implement a method AddSheet(IEnumerable objects, string sheetName) that does the same, just to be easier to use, do you agree with that @mganss?
mganss commentedon Aug 18, 2022
@bh-schmidt Generally, yes. But I wouldn't use the
Stream.Nullhack but rather refactor the coreSave()method to not callWorkbook.Write()at the end:ExcelMapper/ExcelMapper/ExcelMapper.cs
Lines 1026 to 1069 in 2d36c9b