Convert excel workbook to byte[]

I have an “excel library” workbook and want to convert it to a byte[] so I could return the data with the File method exist in asp.net mvc controller.
There are “Save” and “SaveToStream” method, but no convert to byte[].

How can I return the excel file without saving it in server before?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If you have a SaveToStream you could pass in a MemoryStream into that method. Then, once all the bytes are written call ToArray() on the memory stream, which should give you a byte array.

Method 2

Do you need to convert it to a byte[]? File can also return a stream.

Workbook workbook = new Workbook();
Worksheet worksheet = new Worksheet("First Sheet");
worksheet.Cells[0, 1] = new Cell(9999999);

workbook.Worksheets.Add(worksheet);

MemoryStream m = new MemoryStream();
workbook.SaveToStream(m);

return File(m, "application/vnd.ms-excel");


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x