Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XLWorkbook to MemoryStream ends up empty

Tags:

c#

asp.net

azure

I currently have this two methods:

private void UploadOrderToAzure(XLWorkbook workbook, string filename)
    {
        using (var memoryStream = new MemoryStream())
        {
            workbook.SaveAs(memoryStream);
            _azureBlobService.UploadOrder(memoryStream, filename + ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }
    }

public void UploadOrder(Stream item, string name, string contentType)
    {
        CloudBlockBlob azureBlockBlob = OrderContainer.GetBlockBlobReference(name);
        azureBlockBlob.Properties.ContentType = contentType;
        // 3 months cache
        azureBlockBlob.Properties.CacheControl = "max-age=7776000, must-revalidate";
        azureBlockBlob.UploadFromStream(item);
    }

The first method receives an XLWorkbook correctly, it's not empty.

The azureBlockBlob.UploadFromStream(item); line of the last method should also be working correctly.

Somewhere in the middle something goes wrong and I end up with a "corrupted" (Excel tells me it's corrupted but it might be because it has nothing inside) 0 B document.

Am I missing something when trying to manipulate the MemoryStream?

like image 830
muchotaco Avatar asked Feb 16 '26 21:02

muchotaco


1 Answers

A MemoryStream is like the old-school VHS tapes: it doesn't rewind itself. You've written to it - the position is now at the end. If you start reading (UploadFromStream), there is nothing to read. You need to rewind first:

workbook.SaveAs(memoryStream);
memoryStream.Position = 0;
_azureBlobService.UploadOrder(memoryStream, filename + ".xlsx", 
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
like image 98
Marc Gravell Avatar answered Feb 18 '26 11:02

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!