首页 > 解决方案 > 从核心 API 返回 Excel 文件

问题描述

我有 dotnet Core API,它返回 excel 文件(使用 ClosedXML)数据并以角度 API 方法使用此 API

   using (MemoryStream stream = new MemoryStream())
        {
            var workbook = new XLWorkbook();

            var SheetNames = new List<string>() { "15-16", "16-17", "17-18", "18-19", "19-20" };

            foreach (var sheetname in SheetNames)
            {
                var worksheet = workbook.Worksheets.Add(sheetname);

                worksheet.Cell("A1").Value = sheetname;
            }

            workbook.SaveAs(stream);
            stream.Seek(0, SeekOrigin.Begin);

            return this.File(
                fileContents: stream.ToArray(),
                contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",

                // By setting a file download name the framework will
                // automatically add the attachment Content-Disposition header
                fileDownloadName: "ERSheet.xlsx"
            );
        }

以角度传递 API 请求的标头

   'Content-Type': 'aapplication/vnd.ms-excel',
    'Authorization': 'Bearer ' + token
 

在控制台返回数据API 响应

这是我从 API 获得角度响应后的代码

  download(data: Blob) { 
const contentType = 'application/vnd.openxmlformats-ficedocument.spreadsheetml.sheet'; 
const blob = new Blob([data], { type: contentType });
const url = window.URL.createObjectURL(blob);
window.open(url);

}

但这不起作用。任何想法如何从 API 返回 excel 文件数据并通过单击按钮在角度侧下载。

标签: angularasp.net-coreclosedxml

解决方案


推荐阅读