注:此文是经过学习其他然后经过项目实际测试正常时的情况下,做此备份,待后期拓展,
解决问题:通过后台发送Json数据,生成Excel及下载一系列功能均在前端实现,无需后台做专门的Excel。有以下3个步骤
1.在vue项目中安装xlsx库;npm install --save xlsx 代码如1.1
npm install --save xlsx
2.运行项目,创建下边代码文件(命名自定(eg:ExportXlsx.js)),代码如2.1
//代码2.1
import XLSX from 'xlsx';
/**
* 导出Excel的处理函数--针对table
* @param {Array} headers: [{key: 'date', title: '日期'}, {key: 'name', title: '名称'}]
* @param {Array} data : [{date: '2019-05-31', name: 'megen.huang'}, {date: 'name', name: '小明'}]
* @param {String} fileName: '导出结果.xlsx'
* */
export default function ExportExcel(headers, data, fileName = '导出结果.xlsx') {
const _headers = headers
.map((item, i) => Object.assign({}, {
key: item.key,
title: item.title,
position: String.fromCharCode(65 + i) + 1
}))
.reduce((prev, next) => Object.assign({}, prev, {
[next.position]: {
key: next.key,
v: next.title
}
}), {});
const _data = data
.map((item, i) => headers.map((key, j) => Object.assign({}, {
content: item[key.key],
position: String.fromCharCode(65 + j) + (i + 2)
})))
// 对刚才的结果进行降维处理(二维数组变成一维数组)
.reduce((prev, next) => prev.concat(next))
// 转换成 worksheet 需要的结构
.reduce((prev, next) => Object.assign({}, prev, {
[next.position]: {
v: next.content
}
}), {});
// 合并 headers 和 data
const output = Object.assign({}, _headers, _data);
// 获取所有单元格的位置
const outputPos = Object.keys(output);
// 计算出范围 ,["A1",..., "H2"]
const ref = `${outputPos[0]}:${outputPos[outputPos.length - 1]}`;
// 构建 workbook 对象
const wb = {
SheetNames: ['mySheet'],
Sheets: {
mySheet: Object.assign({},
output, {
'!ref': ref,
// eslint-disable-next-line
'!cols': headers.map(item => ({
wpx: 100
}))
}
)
}
};
// 导出 Excel
XLSX.writeFile(wb, fileName);
}
3.在项目的导出方法里待数据返回成功,传入数据和表头,直接调用其方法ExportExcel(表头,数据内容,导出的文件)来导出Excel,代码如3.1(注:先引入2中的文件)
//代码3.1
//这是我的一个后台给数据的接口
getAllDataJF(params).then((res) => {
if (res != "" && res.code == 200) {
if (res.data.dataList.length > 0) {
//执行方法,生成Excel----防止为Null时导致导出Excel出错
const dataSource = res.data.dataList.map(item => {
Object.keys(item).forEach(key => {
if (item[key] === null) {
item[key] = '';
}
if (Array.isArray(item[key])) {
item[key] = item[key].join(',');
}
});
return item;
});
//自定义表头(也可有后台给你传入)
const columns = [{
key: 'idName',
title: 'xx名称'
}
];
exportExcel_(columns, dataSource, `${new Date().getTime().toString()}_导出.xlsx`);
} else {
//数据为空,提示内容即可
}
} else {
console.error("getDataJF 获取失败...");
}
});