Joshua Deshazer
Joshua Deshazer

Reputation: 193

trying to export to excel with epplus core and .net core

I am trying to do an export to excel button when it gets hit I want to call this api and download an excel sheet.

my controller code looks like this and I am honestly stuck because I am unsure what I should be returning back. I am new to .net core api sorry

[Route("api/excel")]
public class ExportToExcel : Controller
{
    private readonly ScadaContext _context;

    public ExportToExcel(ScadaContext context)
    {
        _context = context;
    }

    // GET: api/values
    [HttpGet]
    public ActionResult GetExcelMainView()
    {
        var query = _context.Main_View.Where(x => !x.MeterId.StartsWith("HOGC"));
        List<Object[]> MainViewList = new List<Object[]>();
        foreach(var p in query)
        {
            MainViewList.Add(new Object[] { "Battery Voltage", p.BatteryVoltage });
        }
        MemoryStream stream = new MemoryStream();
        using (ExcelPackage pck = new ExcelPackage(stream)) 
        {
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add("MainView");
            ws.Cells["A1"].LoadFromArrays(MainViewList);
            Response.Clear();
            Response.Headers.Add("content-disposition", "attachment;  filename=Clients.xlsx");
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            var bytes = pck.GetAsByteArray();
            Response.Body.WriteAsync(bytes, 0, bytes.Length);
        }
    }
}

Upvotes: 1

Views: 7869

Answers (1)

Chris F Carroll
Chris F Carroll

Reputation: 12360

Your simplest way to use one of the FileResult subclassess, such as FileStreamResult

The controller method File(stream,...,...) does it for you:

return File(stream, contentTypeString, willbeSavedWithThisFileName);

should just work. I'm not sure if you'll have to re-"wrap" your package in a memorystream again

var streamagain = new MemoryStream(package.GetAsByteArray());

(with the "handrolled" code you've already written, I'd try return StatusCode(200) as the way to get your Content back to the client).

Upvotes: 2

Related Questions