0

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 };
        }
    }
}
s15199d
  • 7,261
  • 11
  • 43
  • 70
  • https://stackoverflow.com/questions/20830309/download-file-using-an-ajax-request – Francois Botha Aug 24 '23 at 19:25
  • I read somewhere yesterday that you can only do File Download from a Synchronous request. So, I changed it to a Synchronous Get and that worked. – s15199d Aug 25 '23 at 13:06

0 Answers0