在Angular 4上导出到Excel [英] Export to Excel on Angular 4

查看:444
本文介绍了在Angular 4上导出到Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a data table that is dynamically populated using Angular 4. I would like to export the table to excel. How can I achieve this in Angular 4. I'm looking for .xls and not .csv.

PS:我不想使用Jquery库.

PS: I don't want to use Jquery libraries.

我的应用程序组件看起来像这样,

My app-component looks like this,

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

推荐答案

您可以使用XLSX导出到excel.

You can use XLSX for export to excel.

它将支持json或excel数组.

It will support json or array into excel.

示例代码

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);
}

保存

private saveAsExcelFile(buffer: any, fileName: string): void {
  const data: Blob = new Blob([buffer], {
    type: EXCEL_TYPE
  });
  const today = new Date();
  const date = today.getFullYear() + '' + (today.getMonth() + 1) + '' + today.getDate() + '_';
  const time = today.getHours() + "-" + today.getMinutes() + "-" + today.getSeconds();
  const name = fileName + date + time;
  FileSaver.saveAs(data, name + EXCEL_EXTENSION);
}

Angular 2+的参考

Reference for Angular 2+

角度2+的Xlsx

这篇关于在Angular 4上导出到Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆