首页 > 解决方案 > 调用WEB API下载excel文件

问题描述

下面是生成 Excel 的 C# WEB API 代码:

public class FileExportController : ApiController
{

    [HttpGet]
    public HttpResponseMessage Get()
    {
        var callerContext = CallerContext.DefaultCallerContext;
        ReportingInput userInput = new ReportingInput();
        userInput.ClientOneCode = "AVON";
        string handle = Guid.NewGuid().ToString();
        var @event = new GetJobReprotDataBlEvent(callerContext, userInput);
        WebApiApplication.ApplicationInitializerObj.EventBus.Publish(@event);
        XLWorkbook wb = new FileExportEngine().ExportExcel(@event.ReportData); //this is returning XLWorkbook
        string fileName = "JobReport_" + DateTime.Now.ToString("yyyy -MM-dd HH':'mm':'ss") + ".xlsx";
        using (MemoryStream memoryStream = new MemoryStream())
        {
            wb.SaveAs(memoryStream);

            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new ByteArrayContent(memoryStream.ToArray())
            };
            result.Content.Headers.ContentDisposition =
                new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = fileName
                };
            result.Content.Headers.ContentType =
                new MediaTypeHeaderValue("application/octet-stream");

            return result;
        }

    }

当我从浏览器调用这个 API 时,我能够生成 excel 文件。 http://localhost/ETLScheduler/api/FileExport - 在浏览器中直接点击时有效

现在我想在 Angular 5 应用程序中使用这个 API。我有一个按钮。点击按钮时,我调用组件方法 downloadFile() 来下载文件。下面是代码:

downloadReport() {     
    this._service.downloadJobReport('AVON');
}

其中 downloadJobReport() 在我的服务文件中,如下所示:

downloadJobReport(clientCode: string) {
    return this._http.get(APIs.downloadJobReport);
}

当我运行应用程序并单击下载按钮时,我什么也没得到,我的意思是文件没有下载。谁能知道,我应该如何更新我的角度代码来使用 API。

提前致谢。

标签: c#angularasp.net-web-apiclosedxml

解决方案


问题是,Angular 期望 JSON 作为结果。您需要配置您的 GET 请求,以便它期望不同的东西。

public downloadJobReport(clientCode: string)): Observable<Blob> {   
    return this._http.get(APIs.downloadJobReport, { responseType: 'blob' });
}

只是一个小问题,您将参数 clientCode 传递给 downloadJobReport,但从不使用它。也许明智的把它排除在外?


推荐阅读