原版文档地址 Vue.js+element-ui+js-xlsx 解析文件内容
此文是在改文档上做出更改适应ant框架
1.首先执行: npm install xlsx (安装)
2.在当前页面.vue文件中引入: import XLSX from ‘xlsx’
3.在main.js中引入:import XLSX from ‘xlsx/dist/xlsx.full.min.js’
4.vue+ant
<div class="">
<a-upload style="display: flex; margin: 5px"
name="file"
:multiple="false"
action="/"
method="post"
accept=".xls, .xlsx"
:headers="headers"
@change="readExcel"
:showUploadList="false"
>
// showUploadList是把文件list隐藏,我也不往后端存,单纯的解析数据,不需要操作list,最关键的是太丑了
<a-button size="small" type="sive">文件</a-button>
</a-upload>
<a-table
:columns="uploadColumns"
:data-source="uploadData"
:pagination="false"
>
</a-table>
</div>
5.data
uploadData: [], //文件数据
fileData: '', // 保存选择的文件
//上传文件请求头,我这个没走后端,没啥用,姑且放这吧
headers: {
authorization: "authorization-text",
},
uploadColumns: [
{
dataIndex: "sort",
key: "sort",
title: "序号",
},
{
dataIndex: "name",
key: "name",
title: "姓名",
},
{
dataIndex: "phone",
key: "phone",
title: "手机号",
}
],
6.js
// 读取数据,比较离谱的是,每次上传文件它都执行了三次change
readExcel(files) {
this.fileData = files // 保存当前选择文件
let that = this
// console.log(files.file.originFileObj)
let type = files.file.name.split('.');
if (!files) {
//如果没有文件
return false
} else if (type[type.length - 1] !== 'xlsx' && type[type.length - 1] !== 'xls') {
this.$message.error("上传格式不正确,请上传xls或者xlsx格式")
return false
}
const fileReader = new FileReader()
// 如果为原生 input 则应是 files[0]
fileReader.readAsBinaryString(files.file.originFileObj)
fileReader.onload = ev => {// 异步执行
try {
const data = ev.target.result
const workbook = XLSX.read(data, {
type: "binary"
})
console.log(workbook.SheetNames)
const wsname = workbook.SheetNames[0] //取第一张表
const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) //生成json表格内容
console.log(ws)
that.uploadData = [] //清空接收数据
for (var i = 0; i < ws.length; i++) {
var sheetData = {
// 键名为绑定 el 表格的关键字,值则是 ws[i][对应表头名]
sort: i+1,
name: ws[i]['姓名'],
phone: ws[i]['手机号'],
}
that.uploadData.push(sheetData)
}
} catch (ev) {
return false;
}
}
}