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);
}