How to return an Excel file from ASP.NET Core Web API web-app?

后端 未结 4 1725
情话喂你
情话喂你 2020-12-31 09:47

In similar questions, with this code works to download a PDF:

I\'m testing with local files (.xlsx, .pdf, .zip) inside the Controller folder.

4条回答
  •  梦谈多话
    2020-12-31 10:37

    My (working) solution:

    • I've got a class that dynamically creates an XLSX file using EPPlus.Core.
      • This returns a FileInfo for the generated file's path.

    This is what is in my Controller:

    [HttpGet("test")]
    public async Task Get()
    {
        var contentRootPath = _hostingEnvironment.ContentRootPath;
    
        // "items" is a List of DataObjects
        var items = await _mediator.Send(new GetExcelRequest());
    
        var fileInfo = new ExcelFileCreator(contentRootPath).Execute(items);
        var bytes = System.IO.File.ReadAllBytes(fileInfo.FullName);
    
        const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        HttpContext.Response.ContentType = contentType;
        HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
    
        var fileContentResult = new FileContentResult(bytes, contentType)
        {
            FileDownloadName = fileInfo.Name
        };
    
        return fileContentResult;
    }
    

    And here is what I have in Angular2:

    downloadFile() {
        debugger;
        var headers = new Headers();
        headers.append('responseType', 'arraybuffer');
    
        let url = new URL('api/excelFile/test', environment.apiUrl);
    
        return this.http
            .get(url.href, {
                withCredentials: true,
                responseType: ResponseContentType.ArrayBuffer
            })
            .subscribe((response) => {
                let file = new Blob([response.blob()], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                let fileName = response.headers.get('Content-Disposition').split(';')[1].trim().split('=')[1];
                saveAs(file, fileName);
            },
            err => this.errorHandler.onError(err)
            );
    }
    

提交回复
热议问题