如何以角度2下载Excel文件

时间:2017-09-11 13:41:18

标签: excel angular download response

我正在学习Angular 2,我试图通过使用web api从sql server表中获取客户数据来下载角度为2的Excel文件。

在谷歌搜索后,我发现了一些代码,但使用该代码我能够下载,但它不包含正确的数据,文件名也有一些guid格式

以下是我使用的代码:

组件

GetRemindersData()
{
    var Flag="ALL_SPOTCHECK_RECORDS";
    this.httpService.GetRemindersData(Flag).subscribe(
        data=>this.downloadFile(JSON.stringify(data[1])),
        error => console.log("Error downloading the file."),
        () => console.info("OK"));
}

downloadFile(data:any){
    console.log(data);
    var blob = new Blob([data], { type: 'application/vnd.ms-excel' });
    var url= window.URL.createObjectURL(blob);
    window.open(url);
}

Service.ts

public GetRemindersData(Flag:string){
    var GetRemindersData_URL:string = 'http://localhost:5000/api/RemindersData/?Flag='+Flag;
    return this.http.get(`${GetRemindersData_URL}`)
                .map((res:Response) => res.json())
                .catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}

1 个答案:

答案 0 :(得分:1)

服务返回json,它必须返回blob类型,你可以这样做

return this.http.get(url,{responseType: ResponseContentType.Blob }).map(
    (res) => {
        return new Blob([res.blob()], { type: 'application/vnd.ms-excel' })
    })

另请查看此帖angular2 file downlaod

相关问题