Angular 7-使用FileSaver.js下载不起作用的Excel文件

时间:2019-03-03 06:07:12

标签: excel angular filesaver.js

我正在向我的后端发送发布请求以接收Excel文件。我可以在邮递员中看到我的后端正在发送Excel,但是在Angular中,我无法使用FileSaver.Js库下载它。有任何想法吗?

这是我的html标记:

<button (click)="excel()">Export Excel</button> 

这是我的服务班级:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import * as FileSaver from 'file-saver';
import 'rxjs';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
    constructor(private data: DataService , private formBuilder: FormBuilder ) { }

    ngOnInit()  {
    }

    excel() {
        this.data.excel().toPromise()
            .then(response => this.saveToFileSystem(response));
    }

    private saveToFileSystem(response) {
        const contentDispositionHeader: string = response.headers.get('Content-Disposition');
        const parts: string[] = contentDispositionHeader.split(';');
        const filename = parts[1].split('=')[1];
        const blob = new Blob([response._body], { type: 'text/plain' });

        FileSaver.saveAs(blob, filename);
    }
}

这是我请求后端的数据类方法:

excel() {
    const headers = new HttpHeaders();
    console.log("sentin")
    headers.set('Content-Type', 'application/json; charset=utf-8');
    return this.http.post(this.baseUrl + '/Excel', { headers: headers })
}

1 个答案:

答案 0 :(得分:0)

最后的答案:

我应该进行以下更改:

  1. 将方法saveFileSystem更改为:

    private saveToFileSystem(response) {
        const blob = new Blob([JSON.stringify(response.body)], { type: 'application/vnd.ms-excel;charset=utf-8' });
        FileSaver.saveAs(blob, "Report.xls");
    }
    
  2. 像这样向我的HttpPost添加响应类型:

    { responseType: 'text' }