前端生成xlsx_node生成表格_xlsx生成样式_excel下载
2025-11-03 03:10:08
表格作为日常数据统计的工具十分常见,如果在项目中需要生成excel该怎么做呢?
3182
前端生成xlsx方法居多的是使用xlsx插件,如果需要添加样式需要xlsx-style,但是这个插件在本地库会有两个问题:
- 直接引入报错
- 无法设定高度
所以改动了代码并上传到npm,可以使用
cnpm i pc-xlsx-style --save
安装插件
const XLSX = require(''pc-xlsx-style'');
async xlsx(header, data,title,time) {
//添加头部
let temp = {};
let compare_head = {};//定位
let _header = header.map((e, i) => {
let postion = i > 26 ? getCharCol(i) : String.fromCharCode(66 + i);
compare_head[e.tag] = postion;
return Object.assign({}, {
v: e.name,
position: postion
});
});
//注意顺序不能乱
temp[''B1'']={
v:title,
s:{
font: {
name: ''微软雅黑'',
sz: 24,
bold: true,
}
}
};
temp["B2"]={
v:time,
s:{
font: {
name: ''微软雅黑'',
sz: 12,
bold: false,
}
}
};
_header.forEach((e,i) => {
temp[e.position + 3] = {
v: e.v,
s:{
font : {
sz: 11,
name: ''微软雅黑'',
color: { rgb: "ffffff" }
},
border:{
top:{
style:''thin''
},
right:{
style:i==_header.length-1?''thin'':null
},
left:{
style:''thin''
},
bottom:{
style:''thin''
}
},
alignment:{
vertical: "center",
horizontal: ''年纪''.indexOf(e.v)>=0?''right'':''left''
},
fill :{
fgColor: { rgb: "808080" }
}
}
};
});
data.forEach((e, i) => {
let index = 0;
for (let obj in e) {
let positon = compare_head[obj] + (4 + i);
// positon,_header[_header.length-1].position
temp[positon] = {
v: e[obj],
s:{
font : {
name: ''微软雅黑'',
sz: 11
},
alignment:{
vertical: "center"
},
border:{
right:{
style:positon.indexOf(_header[_header.length-1].position)>=0?''thin'':null
},
left:{
style:''thin''
},
bottom:{
style:''thin''
}
},
},
t:typeof e[obj]===''number''?''n'':''s''
};
console.log("UtilService -> typeof e[obj]===''number''", typeof e[obj]===''number'',e[obj],typeof e[obj])
index++;
}
})
const outputPos = Object.keys(temp);
const ref = outputPos[0] + '':'' + outputPos[outputPos.length - 1];
const workbook = {
SheetNames: [''mySheet''],
Sheets: {
''mySheet'': Object.assign({}, temp, { ''!ref'': ref })
}
};
let name = ''output'' + new Date().getTime() + ''.xlsx'';
await XLSX.writeFile(workbook, name, {
// showGridLines: false
});
//这里是生成文件
return name;
}
如果在node上还可以使用如下代码
const filePath = ''./'' + name;
this.ctx.attachment(filePath);
this.ctx.set(''Content-Type'', ''application/octet-stream'');
this.ctx.body = fs.createReadStream(filePath);
fs.unlinkSync(filePath);
传递到前端
