angular4 下载文件 Excel zip包
1.下载Excel 文件
import { ResponseContentType } from '@angular/http'; exportInternalOrder(body) { let user_token: string = this.sessionService.getToken(); let headers = new Headers(); headers.append('Authorization', 'Bearer ' + user_token); return this.http.post(this.config.exportInternalOrder, body,{ headers: headers, responseType: ResponseContentType.Blob }).map(res => new Blob([res._body],{ type: 'application/vnd.ms-excel' })); }
2.下载ZIP
var a = document.createElement('a'); var blob = new Blob([responseData], {'type':"application/octet-stream"}); a.href = URL.createObjectURL(blob); a.download = "filename.zip"; a.click();
浏览器有时候会拦截窗口 所以下载excel zip 文件的时候创建a标签下载 保存到本地即可。如上zip下载示例。
下载示例:
/** * 请求成功之后保存成excel文件(基本导出方法,请求成功之后调用) * @param data * @param name */ public saveExcel(data: Response,name:string){ var a = document.createElement('a'); var blob = new Blob([data], {'type':"application/vnd.ms-excel"}); a.href = URL.createObjectURL(blob); a.download = name+".xls"; a.click(); } public down(startDate:String,endDate:String):Promise<any>{ const url= `rest/report/export?startDate=`+startDate+'&endDate='+endDate; return this.http.get(url,{responseType: ResponseContentType.Blob}).toPromise().then(res=>{ //return res.json() as any; this.saveExcel(res.json(),"表一"); }) }