【问题标题】:Angular 7 - using FileSaver.js to download an Excel file not workingAngular 7 - 使用 FileSaver.js 下载 Excel 文件不起作用
【发布时间】:2020-05-16 10:00:32
【问题描述】:

我正在向我的后端发送一个发布请求以接收 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 })
}

【问题讨论】:

标签: excel angular filesaver.js


【解决方案1】:

终于有了答案:

我应该做出这些改变:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2017-12-14
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    相关资源
    最近更新 更多