簡體   English   中英

如何在Angular 2中下載Excel文件

[英]How to download Excel file in angular 2

我正在學習Angular 2,並且嘗試通過使用Web API從sql server表中獲取客戶數據來下載angular 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'));
}

服務返回json,必須返回blob類型,您可以這樣做

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

也看看這篇文章angular2文件下載

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM