2

I need to generate a Excel file in my webAPI in ASP.NET Core with the data received from a aurelia web app. The flow is this: In frontend I make the request

Print(printData: PrintData) {
return this.http
  .fetch(`planning/Print`, {
    method: "post",
    body: json(printData)
  })
  .then(response => response.json())
  .catch(error => {
    console.log(error);
  });

}

In web API Controller I get the data and generate the Excel file using the ClosedXML library

[HttpPost]
[Route("Print")]
public async Task<IActionResult> Print([FromBody] PrintDataVM data)
{      

  var getResponse = await mediator.Send(new PrintPlanning(data));

  return Ok(getResponse);

public async Task<XLWorkbook> PrintPlanning(PrintDataVM data)
  {
    using (XLWorkbook workBook=new XLWorkbook())
    {
      var workSheet= workBook.Worksheets.Add("Horas");

       workSheet.Cell("A1").Value = "Hola";

      return workBook;    
    }

In my controller getResponse is this getResponse

getResponse

and here my doubts begin because I don't know if I should get this obtejct or a memorystream. I do not know how to make the frontend get this so that once received I can treat it there. Right now this gives me error obviously

Any idea please?

Regards

error fetch

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
kintela
  • 1,283
  • 1
  • 14
  • 32

2 Answers2

4

Save your file to stream and return file

var getResponse = await mediator.Send(new PrintPlanning(data));

var ms = new MemoryStream();
getResponse.SaveAs(ms);
ms.Position = 0;
return File(ms, "application/octet-stream", "filename");

or use application/vnd.openxmlformats-officedocument.spreadsheetml.sheet instead of application/octet-stream

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
2

You can use this extension to simplify things: https://www.nuget.org/packages/ClosedXML.Extensions.WebApi/

Usage

In your WebApi controller define an action that will generate and download your file:

public class ExcelController : ApiController
{
    [HttpGet]
    [Route("api/file/{id}")]
    public async Task<HttpResponseMessage> DownloadFile(int id)
    {
        var wb = await BuildExcelFile(id);
        return wb.Deliver("excelfile.xlsx");
    }

    private async Task<XLWorkbook> BuildExcelFile(int id)
    {
        //Creating the workbook
        var t = Task.Run(() =>
        {
            var wb = new XLWorkbook();
            var ws = wb.AddWorksheet("Sheet1");
            ws.FirstCell().SetValue(id);

            return wb;
        });

        return await t;
    }
}

Disclaimer: I'm the author.

Francois Botha
  • 4,520
  • 1
  • 34
  • 46