6

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?

gdoron
  • 147,333
  • 58
  • 291
  • 367

2 Answers2

8

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.

blowdart
  • 55,577
  • 12
  • 114
  • 149
  • 3
    Could you provide some code here? I tried but the Excel file is broken. – Weifeng Sep 13 '16 at 08:48
  • If I have a *SaveToStream*? Checked my desk drawer, didn't find it there. If you have another sentence maybe this might be useful. – EllieK Jul 20 '21 at 20:12
1

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");
Dallas
  • 2,217
  • 1
  • 13
  • 13
  • Thanks, but that doesn't work because the memorty stream isn't in the beginning. so I wrote ToArray(). – gdoron Nov 24 '11 at 08:17