1.下载xlsx插件
npm install xlsx --save
2.封装导出函数,创建文件export.js
import * as XLSX from "xlsx";
function exportExcel(json, name, titleArr, exportTitleName) {
/* 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);
}
}
}
data.push(rowDataArray);
}
}
// keyArray为英文字段表头
data.splice(0, keyArray, 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, exportTitleName);
/* generate file and send to client */
XLSX.writeFile(wb, name + '.xlsx');
}
export default exportExcel
3.页面中使用,先导入文件,再写方法
import exportExcel from "../../../export.js"
const exportBtn = () => {
axios.get('/stu/list').then((res) => {
const titleArr = [
"id",
"手机号",
"姓名",
"月份",
"日期",
]
const exportdataList = []
if (res.errno == 0) {
for (let i of res.data.List) {
let tempdataList = {
'id': i.id,
'phone': i.phone,
'name': i.name,
'month': i.month,
'date': i.date,
}
exportdataList.push(tempdataList)
}
exportExcel(exportdataList, '学生信息', titleArr, 'sheetName');
}
})
}
或许你会有疑问,为什么要加tempdataList?因为返回的数据有些是不需要导出的,如果返回数据全部需要导出的话也可以不需要这个对象,直接导出res.data.List就行