一、需要安装0.15.6
版本的xlsx,否则会出现错误
npm install xlsx@0.15.6
二、页面按需引入
import xlsx from "xlsx"
三、HTML页面
<template>
<div class="less">
<el-button type="primary">excel文件导入</el-button>
<input type="file" name="" id="" @change="fileChange">
<el-table
:data="tableData"
border
style="width: 100%">
<el-table-column
v-for="(v,index) in tableColum" :key="index"
prop="k"
:label="v"
width="width">
<template slot-scope="scope">
{{scope.row[index]}}
</template>
</el-table-column>
</el-table>
</div>
</template>
四、JS
<script>
import xlsx from 'xlsx';
export default {
name: "",
props: [],
data() {
return {
tableData:[], //表格配置数组
tableColum:[]//表头配置数组
};
},
components: {},
computed: {},
beforeMount() {},
mounted() {},
methods: {
fileChange(e){
let file = e.target.files[0];
let reader = new FileReader();
reader.readAsBinaryString(file);//将上传的Excel文件转换为二进制字符串
reader.onload = () =>{
let data = reader.result;
let workbook = xlsx.read(data, {type: 'binary'});//使用XLSX.read方法将该字符串解析成一个JavaScript对象
let worksheet = workbook.Sheets[workbook.SheetNames[0]];//workbook.Sheets属性获取该表单的数据 workbook.SheetNames[0]获取Excel表格的第一个Sheet表单的名称
let json = xlsx.utils.sheet_to_json(worksheet, {header:1});//将表单的数据解析成一个JavaScript数组
this.tableData = json.slice(1);
this.tableColum = json[0];
}
}
},
watch: {},
};
</script>