【问题标题】:Calling WEB API to download excel file调用WEB API下载excel文件
【发布时间】:2019-01-25 13:19:21
【问题描述】:

以下是生成 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。

提前致谢。

【问题讨论】:

  • 您是否检查过downloadJobReport方法是否正在执行,是否检查过API方法是否被调用?

标签: c# angular asp.net-web-api closedxml


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢@nikneem 我现在可以下载文件了,我已经更新了你上面提到的服务代码。我还将控制器代码更新为: this._service.downloadJobReport('AVON').subscribe(data => this.downloadFile(data) );
  • 其中 downloadFile() 为:downloadFile(data: Blob) { const contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; const blob = new Blob([data], { type: contentType });常量 url = window.URL.createObjectURL(blob);窗口.打开(网址); }
  • 感谢您的回复,您能否“接受”答案,以便人们知道答案对您有用?您可以通过单击我的答案旁边的复选标记来做到这一点。
  • 我将参数 clientCode 传递给 downloadJobReport,我将在我的 API 中传递它(我将更新 API 代码)
  • 你知道使用 Angular 下载 excel 的其他方法吗(使用 ASP.Net WEB API),如果你能分享一些正在工作的链接/资源,这将对我有所帮助
【解决方案2】:

正如您在 cmets 中提到的,您正在使用以下角度代码下载文件:

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

我也尝试过这段代码,它在 chrome 浏览器中运行,但在 IE 和 edge 中不运行。

你可以像下面这样更新你的方法:

var downloadFile=function (file_name, content) {
var csvData = new Blob([content], { type: 'text/csv' });
if (window.navigator && window.navigator.msSaveOrOpenBlob) { // for IE
    window.navigator.msSaveOrOpenBlob(csvData, file_name);
} else { // for Non-IE (chrome, firefox etc.)
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    var csvUrl = URL.createObjectURL(csvData);
    a.href =  csvUrl;
    a.download = file_name;
    a.click();
    URL.revokeObjectURL(a.href)
    a.remove();
}

};

您可以参考以下链接了解更多信息:

Open links made by createObjectURL in IE11

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-13
    • 2018-02-01
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多