3

I want to create a Excel file dynamically in C# and I need to make it as downloadable in AngularJS HTML Button Click.

I referred the following link to create Excel dynamically http://www.increvcorp.com/manipulating-excel-spreadsheet-using-c/

It's working fine. But it saves the file in local storage

 xlWorkBook.SaveAs("D:\\Mobile_List.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

I referred one more post, they given idea to convert directly from workbook to Memory Stream - Convert excel workbook to byte[].

But, in that post they used the

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

I Can't able to find the method SaveToStream in my workbook, it shows an error

'Microsoft.Office.Interop.Excel.Workbook' does not contain a definition for 'SaveToStream' and no extension method 'SaveToStream' accepting a first argument of type 'Microsoft.Office.Interop.Excel.Workbook' could be found (are you missing a using directive or an assembly reference?)

How could I make it as memory stream and send it back to AngularJS for download by clicking the HTML Button ?

I referred one more post to AngularJS $http-post - convert binary to excel file and download - it purely explained the angularJS part and PHP. There is no explanation for C#, that's the main reason I'm posting this question.

Kindly assist me...

Note: Don't convert it from local storage...

Community
  • 1
  • 1

1 Answers1

0

If your workbook object does cannot be converted to a byte array, you can still work with the file you saved on your disk :

var byteArray = File.ReadAllBytes("PathToSavedWorkBook");
using(var ms = new MemoryStream(byteArray))
{
    //Use your memorystream
}

If you only want a byteArray though, the first line is enough

EDIT:

As per the documentation of the class you are using : https://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.aspx

It seems that it is not possible to not save the workbook in a file

Irwene
  • 2,807
  • 23
  • 48
  • 1
    You could try and save the workbook with [Workbook.SaveCopyAs](https://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.workbook.savecopyas.aspx) in a temporary folder with a timestamp attached to its filename and then read it in again with the method @Sidewinder94 proposed. – Maximilian Riegler Apr 28 '16 at 11:13