js代碼
? ? //下載模板
? ? downloadExl() {
?????// 標題
? ? ? const tHeader = [‘xxx’,'xxx','xx名稱','電槍xx','協議xx','snxx'];
? ? ? // key
? ? ? const filterVal = ['agentName', 'stationName', 'equName', 'channelNumber', 'manufacturer', 'sn', ];
? ? ? ? // 值
? ? ? const datas = [
? ? ? ? {
? ? ? ? ? agentName:? ?'你好',
? ? ? ? ? stationName:? ?'我們',
? ? ? ? ? equName:? ? ? ?'朋友',
? ? ? ? ? channelNumber: '一起',
? ? ? ? ? manufacturer:? '是的',
? ? ? ? ? sn:? ? ? ? ? ?'123456',
? ? ? ? },
? ? ? ];
? ? ? ?// 整合
? ? ? const json=datas.map(v => filterVal.map(j => v[j]));
? ? ? // 導出
? ? ??export_json_to_excel(json,'導出名稱.xlsx'),tHeader,'導出名稱');
? ? },
excel js代碼
import XLSX from "xlsx";
/**
?* 導出excel
?* json 服務端發過來的數據
?* name 導出Excel文件名字
?* titleArr 導出Excel表頭
?* sheetName 導出sheetName名字
?*/
export function export_json_to_excel(json,name,titleArr,sheetName) {
? ? /* convert state to workbook */
? ? var data = new Array();
? ? var keyArray = new Array();
? ? const getLength = function (obj) {
? ? ? ? var count = 0;
? ? ? ? for (var i in obj) {
? ? ? ? if (obj.hasOwnProperty(i)) {
? ? ? ? ? ? count++;
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return count;
? ? };
? ? for (const key1 in json) {
? ? ? ? if (json.hasOwnProperty(key1)) {
? ? ? ? ? ? const element = json[key1];
? ? ? ? ? ? var rowDataArray = new Array();
? ? ? ? ? ? for (const key2 in element) {
? ? ? ? ? ? ? ? if (element.hasOwnProperty(key2)) {
? ? ? ? ? ? ? ? ? ? const element2 = element[key2];
? ? ? ? ? ? ? ? ? ? rowDataArray.push(element2);
? ? ? ? ? ? ? ? ? ? // if (keyArray.length < getLength(element)) {
? ? ? ? ? ? ? ? ? ? // ? ? keyArray.push(key2);
? ? ? ? ? ? ? ? ? ? // }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? if(null!=rowDataArray && rowDataArray.length>0){
? ? ? ? ? ? ? ? console.log('rowDataArray=', rowDataArray);
? ? ? ? ? ? ? ? data.push(rowDataArray);
? ? ? ? ? ? ? ? console.log('data=', data);
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? data.splice(0, 0,titleArr);
? ? console.log('data', data);
? ? const ws = XLSX.utils.aoa_to_sheet(data);
? ? const wb = XLSX.utils.book_new();
? ? // 此處隱藏英文字段表頭
? ? var wsrows = [{ hidden: false }];
? ? ws['!rows'] = wsrows; // ws - worksheet
? ? XLSX.utils.book_append_sheet(wb, ws, sheetName);
? ? /* generate file and send to client */
? ? // XLSX.writeFile(wb, name + '.xlsx');
? ? XLSX.writeFile(wb, name);
}