在Angular 4上导出到Excel

时间:2018-02-15 07:37:34

标签: excel angular

我有一个使用Angular 4动态填充的数据表。我想将表导出到excel。我怎样才能在Angular 4中实现这一目标。 我正在寻找.xls而不是.csv。

PS:我不想使用Jquery库。

我的app-component看起来像这样,

    <table id ="dataTable" class = "table table-hover">
  <thead>
      <tr>
          <th>Date</th>
          <th>Address</th>
          <th>Mode</th>
          <th>Distance</th>
          <th>Fare</th>
          <th></th>
      </tr>
  </thead>
  <tbody>
      <tr *ngFor="let date of dateList;let i = index">
          <td>{{date}}</td> 
          <td>{{address}}</td>
          <td>{{mode}}</td>
          <td>{{distance}}</td>
          <td>{{fare}}</td>
          <td>
             <a>Delete</a>
          </td>   
      </tr>
  </tbody>
</table>

感谢您的提前帮助

4 个答案:

答案 0 :(得分:9)

您可以使用XLSX导出到Excel。

它将支持json或数组进入excel。

示例代码

noexcept

保存

import * as XLSX from 'xlsx';

public exportAsExcelFile(json: any[], excelFileName: string): void {
  const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
  const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
  const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' });
  this.saveAsExcelFile(excelBuffer, excelFileName);
}

Angular 2 +的参考

Xlsx for angular 2+

答案 1 :(得分:1)

您只能使用xlsx来使用XLSX.writeFile()库同时写入和保存excel文件。

exportExcel(data: any[]){
   const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(data);
   const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
   XLSX.writeFile(workbook, 'my_file.xls', { bookType: 'xls', type: 'buffer' });
}

答案 2 :(得分:1)

在安装libary之前

npm i file-saver
npm i xlsx

使用名称类ExcelService创建服务excel ng s excel / ExcelService 您可以在下面的代码中复制

import { Injectable } from '@angular/core';
import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
@Injectable({
  providedIn: 'root'
})
export class ExcelServiceService {
  constructor() { }
  public exportAsExcelFile(json: any[], excelFileName: string): void {

    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
    console.log('worksheet',worksheet);
    const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
    const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    this.saveAsExcelFile(excelBuffer, excelFileName);
  }
  private saveAsExcelFile(buffer: any, fileName: string): void {
    const data: Blob = new Blob([buffer], {
      type: EXCEL_TYPE
    });
    FileSaver.saveAs(data, fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
  }
}

在具有CountryCount类的目录中创建文件夹模型

export class CountryInfo {
    country: string;
    hydro: number;
    oil: number;
    gas: number;
    coal: number;
    nuclear: number;
}

您可以克隆示例以 github

的角度导出excel文件。

答案 3 :(得分:0)

似乎microsoft提供了一个Javascript插件,可以与Angular一起使用,here