使用 JavaScript 导出 Excel 文件
Table of Contents
1 SheetJS
1.1 安装
SheetJS 可以读写 Excel 文件,它的社区版本是开源免费使用的,安装方法如下:
yarn add xlsx
1.2 使用
官网上的使用方法见 sheetjs angular2 。
1.2.1 export-excel.ts
import { Component, OnInit } from '@angular/core'; import * as XLSX from 'xlsx'; type MTI_TABLE_T = any[][]; @Component({ selector: 'app-export-excel', templateUrl: './export-excel.component.html', styleUrls: ['./export-excel.component.less'] }) export class ExportExcelComponent implements OnInit { data: MTI_TABLE_T; option: XLSX.WritingOptions; fileName: string; constructor() { } ngOnInit() { this.data = [ ['姓名', '年龄', '成绩'], ['洛阳铲', 22, 87], ['王大锤', 21, 88], ['李敏镐', 22, 73] ]; this.option = { bookType: 'xlsx', type: 'array' }; this.fileName = 'worksheet.xlsx'; } export(): void { // generate worksheet const worksheet: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(this.data); // generate workbook and add the worksheet const workbook: XLSX.WorkBook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1'); // save to file XLSX.writeFile(workbook, this.fileName); } }
1.2.2 export-excel.html
<div class="export-excel-div"> <h2>导出 Excel 文件到 {{ fileName }}</h2> <table> <tr *ngFor="let row of data"> <td *ngFor="let cell of row"> {{ cell }} </td> </tr> </table> <span> <input [(ngModel)]="fileName"/> <button (click)="export()">export</button> </span> </div>
2 参考链接
- SheetJS: SheetJS Community Edition – Spreadsheet Parser and Writer
- yarn package site: xlsx