如何使用Angular2正确下载Excel文件 [英] How to properly download excel file with Angular2

查看:395
本文介绍了如何使用Angular2正确下载Excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的服务代码,它使带有响应的后请求成为xls文件:

This is the code of my service which makes post request with response an xls file :

exportInternalOrder(body) {
        let user_token: string = this.sessionService.getToken();
        let headers = new Headers();
        headers.append('responseType', 'arraybuffer');
        headers.append('Authorization', 'Bearer ' + user_token);
        return this.http.post(this.config.exportInternalOrder, body,{
            headers: headers
        }).map(res => new Blob([res._body],{ type: 'application/vnd.ms-excel' }));
    }

应该处理excel文件的响应. 这是调用它的代码:

Which is supposed to handle response of excel file. This is the code invoking it:

let objToSend = this.makeObjToSend(false);
this.reportingService.exportExcel(objToSend)
    .subscribe(
        data => {
            this.exportData(data);
        },
        error => {
            this.errorFilterMsg.push({ severity: 'error', detail: 'Report exporting has failed!' });
        }
);

这是文件的保存(出于某种原因,window.open不会执行任何操作):

And this is the saving of the file (for some reason window.open does nothing):

exportData(data){       
        let blob = data;
        let a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = 'fileName.xls';
        document.body.appendChild(a);
        a.click();        
    }

但是文件仍然保存为损坏的文件.使用邮递员和卷曲时,它可以.任何帮助将不胜感激.

But the file still saves as corrupted one. While using postman and curl it comes ok. Any help would be appreciated.

推荐答案

responseType不应在headers中设置,它是RequestOptionsArgs对象的一部分,该对象作为post函数和RequestOptionsArgs包含headersresponseType和其他内容,您可以阅读有关此处.因此,您的代码应如下所示:

responseType shouldn't be set in headers, it's part of RequestOptionsArgs object which is passed as second argument in post function and RequestOptionsArgs contains headers, responseType and others, you can read more about it here. So, your code should look like this:

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' }));
}

这篇关于如何使用Angular2正确下载Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆