I made an API using C# and am using is as a back end for my angular project. I was tasked to save data as am excel file from my page through a button made in angular. The logic is in the back end. I have tried everything to accomplish this, but nothing seems to work. I am using EPPlus now, with the SaveAs method, converting the excel package in a byte array.
So here is my fucntion in C#
public IHttpActionResult CreateExcelDocument()
{
//Creates a blank workbook. Using statement disposes the package.
using (var p = new ExcelPackage())
{
var result = new MemoryStream();
List<Hero> heroes = new List<Hero>();
var documents = collection.Find(new BsonDocument()).ToList();
foreach (BsonDocument docum in documents)
{
heroes.Add(BsonSerializer.Deserialize<Hero>(docum));
}
//Adding worksheet
var ws = p.Workbook.Worksheets.Add("Heroes");
//To set values in the spreadsheet use the Cells indexer.
ws.Cells["A1"].Value = "ID";
ws.Cells["B1"].Value = "Name";
for(var row = 1; row <= heroes.Count(); row++)
{
ws.Cells[row, 1].LoadFromCollection(heroes[row].Id);
ws.Cells[row, 2].LoadFromCollection(heroes[row].Name);
}
var stream = new MemoryStream(p.GetAsByteArray());
//string filePath = @"c:\workbooks\myworkbook.xlsx";
//FileInfo template = new FileInfo(filePath);
//MemoryStream outputStream = new MemoryStream();
p.SaveAs(stream);
return Ok(stream);
}
}
Here is how it is how angular get it
saveDocument(): Observable<any> {
return this.http.get<any>(this.heroesUrl)
.pipe(
tap(p => this.log('saved excel document' + p)),
catchError(this.handleError<any>('saveDocument', []))
);
}
I made a message component that shows me the status of my API requests, so with saveDocument i an getting this: HeroService: saved excel document[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
I am using MongoDB, Angular 8, and ASP.NET Web API 2 (C#)
EDIT: here is the button in angular
<button (click)="saveDocument()"> Save heroes </button>