Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to write xlsx data into memory stream #38

Open
yoliva opened this issue Dec 23, 2022 · 1 comment
Open

Unable to write xlsx data into memory stream #38

yoliva opened this issue Dec 23, 2022 · 1 comment

Comments

@yoliva
Copy link

yoliva commented Dec 23, 2022

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
Copy link

eoehen commented Mar 11, 2023

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants