youngcm2 / CsvHelper.Excel

Apache License 2.0
65 stars 33 forks source link

Unable to write xlsx data into memory stream #38

Open yoliva opened 1 year ago

yoliva commented 1 year ago

Hi, I'm unable to get the bytes of the xlsx file from the MemoryStream. the code in approach 1 generates the file but in approach 2 I get always an empty byte[]. What I'm missing here? thanks!

Approach 1:
            using (var writer = new ExcelWriter("test_123.xlsx"))
            {
                writer.WriteRecords(sections.ToList());
            }

Approach 2:
            using var stream = new MemoryStream();
            using var writer = new ExcelWriter(stream, CultureInfo.InvariantCulture);
            {
                writer.WriteRecords(sections.ToList());
            }

            var data = stream.ToArray();
            var fileName = $"{DateTime.UtcNow.ToStandardFullFormat()}.{FileExtensions.XLSX}";

            return new DataFile(fileName, ContentTypes.XLSX, FileType, data);
eoehen commented 1 year ago

@yoliva I have found a solution. The data is transferred to the stream during Dispose. But for some reason the Dispose is executed too late. If you call it manually before fetching the BinaryArray, the data is there.

using var stream = new MemoryStream();
using var writer = new ExcelWriter(stream, CultureInfo.InvariantCulture);
{
  writer.WriteRecords(sections.ToList());
}

// ------------------------------------------------
writer.Dispose(); // The daten will transfer to the stream
// ------------------------------------------------

var data = stream.ToArray();
var fileName = $"{DateTime.UtcNow.ToStandardFullFormat()}.{FileExtensions.XLSX}";

return new DataFile(fileName, ContentTypes.XLSX, FileType, data);

This hack is working in my case.