如何在角度2下载Excel文件
我正在学习Angular 2,我试图通过使用web api从sql server表中提取客户数据来以角度2下载Excel文件。如何在角度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 file downlaod
使用上面的代码后,我刚刚得到一个未定义的字符串值excel文件 – user3301440
你可以后端响应 – Robert
支持的响应是json对象数组 – user3301440
您可以创建从数据你前面的Excel文件的文件显示。看看[这里](https://stackoverflow.com/a/44766181)的答案,看看它是如何完成的。 – BogdanC
上述参考后,我有'coudld没有找到模块'xlsx'的声明文件的错误。 '/ node_modules /xlsx/xlsx.js'隐式具有'任何'类型。' – user3301440
我有一个Angular演示应用程序实现'xlsx' [here](https://github.com/bogdancar/xlsx-json-to-xlsx-demo-Angular2)。克隆它,看看它是如何工作的。 – BogdanC