返回

Angular 通过 $http.post 获取二进制 Excel 文件

前端

让我们直接进入如何通过 Angular 中的 $http.post 方法请求并下载二进制 Excel 文件!

1. 引入必要的模块

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

2. 创建一个服务来处理下载

@Injectable()
export class ExcelDownloadService {

  constructor(private http: Http) { }

  downloadExcel(url: string, data: any): Observable<Response> {
    const headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post(url, data, { headers: headers, responseType: ResponseContentType.Blob });
  }
}

3. 在组件中使用该服务

import { Component, OnInit } from '@angular/core';
import { ExcelDownloadService } from '../excel-download.service';

@Component({
  selector: 'app-excel-download',
  templateUrl: './excel-download.component.html',
  styleUrls: ['./excel-download.component.css']
})
export class ExcelDownloadComponent implements OnInit {

  constructor(private excelDownloadService: ExcelDownloadService) { }

  ngOnInit() { }

  downloadExcel() {
    const url = 'http://localhost:3000/api/excel';
    const data = {
      name: 'John Doe',
      age: 30
    };

    this.excelDownloadService.downloadExcel(url, data).subscribe(response => {
      const blob = new Blob([response.blob()], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const fileName = 'example.xlsx';
      saveAs(blob, fileName);
    });
  }
}

4. 在 HTML 中添加按钮

<button (click)="downloadExcel()">Download Excel</button>

现在,当您点击下载按钮时,Excel 文件将自动下载到您的计算机上。

希望这篇教程对您有所帮助。如果您有任何问题,请随时留言。