安装依赖
npm install node-excel-export
server/ app.js
const excel = require('node-excel-export');
app.get('/api/getexcel', async (req, res) => {
let dataset = await queryAllPlData(req.query) // 这里不做详情介绍,就是通过sql拿到正常的表格数据,具体代码可以参考我的另一篇文章
// excel样式
const styles = {
headerNormal: {
fill: {
fgColor: {
rgb: 'dd4b39'
}
},
border: {
top: { style: 'thin', color: '000000' },
bottom: { style: 'thin', color: '000000' },
left: { style: 'thin', color: '000000' },
right: { style: 'thin', color: '000000' }
},
font: {
bold: true,
sz: 11,
color: {
rgb: 'ffffff'
}
}
},
cellNormal: {
fill: {
fgColor: {
rgb: 'FFFFFF'
}
},
border: {
top: { style: 'thin', color: '000000' },
bottom: { style: 'thin', color: '000000' },
left: { style: 'thin', color: '000000' },
right: { style: 'thin', color: '000000' }
},
font: {
sz: 10
}
},
cellRed: {
// fill: {
// fgColor: {
// rgb: 'ff0000'
// }
// }
border: {
top: { style: 'thin', color: '000000' },
bottom: { style: 'thin', color: '000000' },
left: { style: 'thin', color: '000000' },
right: { style: 'thin', color: '000000' }
},
font: {
sz: 10,
color: {
rgb: 'ff0000'
}
}
},
};
// excel列表头数据
const specification = {
id: {
displayName: 'id',
headerStyle: styles.headerNormal,
cellStyle: styles.cellNormal,
width: '13'
},
sex: {
displayName: '性别',
headerStyle: styles.headerNormal,
cellFormat: function(value, row) {
return (value == 1) ? '男' : '女';
},
cellStyle: function(value, row) {
return (row.sex== 1) ? styles.cellRed : styles.cellNormal;
},
width: '12'
},
remark: {
displayName: '备注',
headerStyle: styles.headerNormal,
cellFormat: function(value, row) {
return value ? value : '-';
},
cellStyle: function(value, row) {
return (row.remark_bgground== 'red') ? styles.cellRed : styles.cellNormal;
},
width: '16'
},
}
// excel配置
const report = excel.buildExport(
[
{
name: 'Report', // <- Specify sheet name (optional)
// heading: heading, // <- Raw heading array (optional)
// merges: merges, // <- Merge cell ranges
specification: specification, // <- Report specification
data: dataset // <-- Report data
}
]
);
res.attachment('下载表.xlsx');
res.send(report);
})
excel.vue
//导出
getexport () {
const { account, name, info } = this.filters // 参数
let url = `api/getexcel?account=${account}&name=${name}&info=${info}`
window.location = url;//这里不能使用get方法跳转,否则下载不成功
},
----------------------------------
有问题欢迎留言~