前端
window.Axios.post(window.ApiName.excelExport, params ,{ responseType: 'blob' })
then((res) => {
var blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
var a = document.createElement('a');
var href = window.URL.createObjectURL(blob); // 创建链接对象
a.href = href;
a.download = 'fileName.xlsx'; // 自定义文件名
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(href); //移除链接对象
document.body.removeChild(a); // 移除a元素
});
// 一定要写响应类型:{responseType: 'blob'}
//Blob返回excel类型 {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}
// 注意是post请求方式
express后台
node-excel-export:数据集创建excel导出时协助的好小模块。它需要正常的对象数组和json报告规范,并构建excel(.xlsx)文件。它支持动态样式和重新格式化
安装模块:npm install --save node-excel-export
var excel = require('node-excel-export');
app.post('/api/excelExport', urlencodedParser, function(req, res){
const styles = {
header: {
font: {
sz: 18,
bold: true,
}
},
headerTitle: {
font: {
sz: 12,
bold: true,
}
},
};
// 标题
const heading = [
[{value:'report标题', style: styles.header}],
];
// 合并
const merges = [
{ start: { row: 1, column: 1 }, end: { row: 1, column: 3 } },
]
// 列结构
const specification = {
school: {
displayName: '学校',
headerStyle: styles.headerTitle,
width: 100,
},
academe: {
displayName: '院系',
headerStyle: styles.headerTitle,
width: 160
},
grade: {
displayName: '年级',
headerStyle: styles.headerTitle,
width: 80
},
}
// 数据
var dataset = [{
school: "a",
academe: "b",
grade: "c",
}]
//生成excel文件的二进制流
const report = excel.buildExport(
[
{
name: 'report',
heading: heading,
merges: merges,
specification: specification,
data: dataset
}
]
);
res.attachment('report.xlsx');
res.end(report);
});