npm install @types/exceljs @types/file-saver file-saver -S
疑問爲何下載了 @types/file-saver
,還下載後面的css
由於會報錯,不信本身試試,後面發現再下載
file-saver
能解決問題html
上代碼npm
import {Component, OnInit} from '@angular/core'; import {Workbook} from 'exceljs'; import { saveAs } from 'file-saver'; @Component({ selector: 'app-count-down', templateUrl: './count-down.component.html', styleUrls: ['./count-down.component.scss'] }) export class CountDownComponent implements OnInit { // 建立一個名字和年齡的數據 json_data = [{ "name": "Raja", "age": 20 }, { "name": "Mano", "age": 40 }, { "name": "Tom", "age": 40 }, { "name": "Devi", "age": 40 }, { "name": "Mango", "age": 40 } ] constructor() { } ngOnInit(): void { } // 節點按鈕直接下載 downloadExcel() { // 建立工做薄 let workbook = new Workbook(); // 將名字添加到工做薄中 let worksheet = workbook.addWorksheet('名字年齡表格') // 添加行的標題 let header = ['名字', '年齡'] worksheet.addRow(header); // 把數據按照一行一行添加到裏面去 for (let item of this.json_data) { worksheet.addRow(Object.values(item)) } // 下載文件名 let fname = '我的資料統計表'; workbook.xlsx.writeBuffer().then(data => { let blob=new Blob([data],{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); saveAs(blob, fname+'-'+new Date().valueOf()+'.xlsx'); }) } }