I'm attempting to allow the user to download a set of data as *.xlsx when they click a button. The code completes without error, but no file is downloaded and I'm stumped.
Index.cshtml
<form class="d-flex flex-row" method="post" asp-page-handler="ExportToExcel" data-ajax="true" data-ajax-method="post" data-ajax-success="alert('done');" data-ajax-failure="ajaxValidationHandler">
<button type="submit" class="btn btn-primary" data-bs-toggle="tooltip" data-bs-placement="top" title="Export to Excel"><i class="fa-light fa-cloud-arrow-down"></i></button>
</form>
Index.cshtml.cs
public ActionResult OnPostExportToExcel()
{
AssetsList = _context.Assets.ToList();
using (var workbook = new XLWorkbook())
{
var worksheet = workbook.Worksheets.Add("Assets");
var currentRow = 1;
worksheet.Cell(currentRow, 1).Value = "AssetName";
// more cols here
foreach (Asset asset in AssetsList)
{
currentRow++;
worksheet.Cell(currentRow, 1).Value = asset.AssetName ?? "";
// more cols here
}
var fileName = "AssetsExport-" + DateTime.Now.ToString("yyyyMMdd-HHmmssfff") + ".xlsx";
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
stream.Position = 0;
var cd = new System.Net.Mime.ContentDisposition
{
FileName = fileName,
Inline = false
};
Response.Headers["Content-Disposition"] = cd.ToString();
return new FileStreamResult(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = fileName };
}
}
}