如何下载MS Excel文件

时间:2018-04-20 16:01:44

标签: javascript node.js angular

我有Node.js服务返回:

Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

这是我的Angular代码下载它。它工作正常:

import { saveAs } from 'file-saver/FileSaver';

getXLS(){
    const type = 'application/vnd.ms-excel';

    const options = new RequestOptions({
        responseType: ResponseContentType.Blob,
        headers: new Headers({ 'Accept': type })
    });

    this.httpService.post(<url>, options)
        .catch(errorResponse => Observable.throw(errorResponse.json()))
        .map((response) => {
            if (response instanceof Response) {
                return response.blob();
            }
            return response;
        }).subscribe(data => saveAs(data, “temp.xlsx”),
        error => console.log(error));
   }
}

但我不想立即保存。我希望我的getXLS()返回该响应。然后通过其他功能

保存
<button class="button" (click)="getXLS()">Save</button>
<button class="button" (click)="doSave()">Save</button>

怎么做?

1 个答案:

答案 0 :(得分:0)

如果您不希望立即下载该文件,请不要在订阅中使用where rownum >=2 and rownum < 4。而只是将响应保存在局部变量中。

saveAs

然后在你的doSave方法中:

getXLS(){
    const type = 'application/vnd.ms-excel';

    const options = new RequestOptions({
        responseType: ResponseContentType.Blob,
        headers: new Headers({ 'Accept': type })
    });

    this.httpService.post(<url>, options)
        .catch(errorResponse => Observable.throw(errorResponse.json()))
        .map((response) => {
            if (response instanceof Response) {
                return response.blob();
            }
            return response;
        }).subscribe(data => this.xmlBlob = data,  //assuming xmlBlob variable will be defined somewhere
        error => console.log(error));
   }
}