下载
npm install @types/exceljs @types/file-saver file-saver -S
疑问为什么下载了 @types/file-saver
,还下载后面的
因为会报错,不信自己试试,后面发现再下载
file-saver
能解决问题
上代码
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');
})
}
}