使用xlsx把json对象导出excel
1,首先使用npm下载xlsx.执行命令 npm install xlsx --save
import { Component, OnInit } from '@angular/core'; //import * as FileSaver from 'file-saver'; import * as XLSX from 'xlsx'; @Component({ selector: 'app-export-as-excel', templateUrl: './export-as-excel.component.html', styleUrls: ['./export-as-excel.component.css'] }) export class ExportAsExcelComponent implements OnInit { /* aa:any; bb:any;*/ /* persons:any=[{ id:'1', name:'zheng', age:'23', surname:'zhengxiaoya' }, { id:'2', name:'xue', age:'24', surname:'saria' } ];*/ /* data = [ ['1','a','aa'], ['2','b','bb'], ['3','c','cc'] ]*/ config: any=[ {主页: "111", 名称: "6800", 数量: "6800", 昵称: "广告主网"}, { 主页: "433", 名称: "6800", 数量: "6800", 昵称: "广告主网"}, { 名称: "22", 商家: "6800", 数量: "6800", 昵称: "广告主网"}, { 名称: "43", 商家: "6800", 数量: "6800", 昵称: "广告主网"}, { 店家: "43", 价格: "6800", 数量: "6800", 昵称: "广告主网"} ] constructor() { } ngOnInit() { /* this.aa=document.getElementById("table1") var as=document.getElementById("table1"); console.log("a", document.getElementById("table1"));*/ }; exportFile(){ /* var date=new Date(); var y = date.getFullYear(); var m = date.getMonth() + 1; var d = date.getDate(); var h = date.getHours(); var mi = date.getMinutes(); var s = date.getSeconds(); var res = y.toString(); if(m < 10) res += "0"; res += m; if(d < 10) res += "0"; res += d; if(h < 10) res += "0"; res += h; if (mi < 10) res += "0"; res += mi; if (s < 10) res += "0"; res += s; console.log("date",date); console.log("format",res);*/ /* generate worksheet */ const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.config); const ws2: XLSX.WorkSheet = XLSX.utils.json_to_sheet(this.config); // const ws: XLSX.WorkSheet = XLSX.utils.table_to_sheet(this.aa); // const ws2: XLSX.WorkSheet = XLSX.utils.table_to_sheet(this.aa); /* generate workbook and add the worksheet */ const wb: XLSX.WorkBook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, 'Sheet1'); // XLSX.utils.book_append_sheet(wb, ws2, 'Sheet2'); console.log(wb) /* if(!wb.Props) wb.Props = {}; wb.Props.Title = "Insert Title Here"+res;*/ /* save to file */ XLSX.writeFile(wb, 'SheetJS.xlsx'); //直接定义死文件名 // XLSX.writeFile(wb, wb.Props.Title+'.xlsx'); // 通过变量设置文件名 } /* F_Open_dialog(){ document.getElementById('btn_file').click(); var objFile = document.getElementById("btn_file"); console.log("dd",objFile); }*/ }
自立更生,艰苦奋斗!