1.安装环境
npm install file-saver --save
npm install xlsx -save
"export ‘default’ (imported as ‘XLSX’) was not found in ‘xlsx’ 当出现类似这样的报错,你可以试一下这个
npm install xlsx@0.16.0 --save
2.对xlsx进行封装 - getXlsx.js
文件路径 utils/getXlsx.js
import fs from 'file-saver'
import XLSX from 'xlsx'
export function xlsx(json, fields, filename = '.xlsx') {
json.forEach(item => {
for (let i in item) {
if (fields.hasOwnProperty(i)) {
item[fields[i]] = item[i];
}
delete item[i];
}
})
let sheetName = filename
let wb = XLSX.utils.book_new()
let ws = XLSX.utils.json_to_sheet(json, {
header: Object.values(fields)
})
wb.SheetNames.push(sheetName)
wb.Sheets[sheetName] = ws
const defaultCellStyle = {
font: {
name: "Verdana",
sz: 13,
color: "FF00FF88"
},
fill: {
fgColor: {
rgb: "FFFFAA00"
}
}
};
let wopts = {
bookType: 'xlsx',
bookSST: false,
type: 'binary',
cellStyles: true,
defaultCellStyle: defaultCellStyle,
showGridLines: false
}
let wbout = XLSX.write(wb, wopts)
let blob = new Blob([s2ab(wbout)], {
type: 'application/octet-stream'
})
fs.saveAs(blob, filename + '.xlsx')
}
const s2ab = s => {
var buf;
if (typeof ArrayBuffer !== 'undefined') {
buf = new ArrayBuffer(s.length)
var view = new Uint8Array(buf)
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
return buf
} else {
buf = new Array(s.length);
for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
}
3.将列表数据进行导出
<el-button style="margin-left: 8px" type="primary" @click="handleExcel">导出</el-button>
<el-table :data="tableList" border fit highlight-current-row>
<el-table-column label="姓名" prop="name" align="center"></el-table-column>
<el-table-column label="性别" prop="gender" align="center"></el-table-column>
<el-table-column label="成绩" prop="score" align="center"></el-table-column>
<el-table-column label="家庭住址" prop="address" align="center"></el-table-column>
</el-table>
import { xlsx } from "@/utils/getXlsx";
tableList: [
{
name: "张三",
gender: "男",
score: "95",
address: "陕西省",
},
{
name: "李四",
gender: "男",
score: "94",
address: "山西省",
},
{
name: "王五",
gender: "男",
score: "91",
address: "上海市",
},
{
name: "张美丽",
gender: "女",
score: "90",
address: "北京市",
},
{
name: "李漂亮",
gender: "女",
score: "88",
address: "云南省",
},
{
name: "贾有钱",
gender: "男",
score: "87",
address: "四川",
},
],
handleExcel() {
let fields = {
title1: "姓名",
title2: "性别",
title3: "成绩",
title4: "家庭住址",
};
let arry = [];
this.tableList.forEach((item) => {
arry.push({
title1: item.name,
title2: item.gender,
title3: item.score,
title4: item.address,
});
});
xlsx(arry, fields, "人员名单");
},
|