.NET Core Razor Pages + ClosedXML + 不显眼的 AJAX = 文件下载失败

.NET Core Razor Pages + ClosedXML + Unobtrusive AJAX = File Download Fail

提问人:s15199d 提问时间:8/24/2023 更新时间:8/24/2023 访问量:46

问:

我试图允许用户在单击按钮时将一组数据下载为 *.xlsx。代码完成没有错误,但没有下载任何文件,我被难住了。

索引.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 };
        }
    }
}
asp.net-core razor-pages closedxml unobtrusive-ajax

评论

0赞 Francois Botha 8/25/2023
stackoverflow.com/questions/20830309/......
0赞 s15199d 8/25/2023
我昨天在某处读到,您只能从同步请求进行文件下载。所以,我把它改成了同步获取,这奏效了。

答: 暂无答案