首先安装依赖
npm install xlsx
代码如下:
<template>
<div class="data">
<input id="file" type="file" @change="readExcel">
<br>
{{outputs}}
</div>
</template>
<script>
import * as XLSX from 'xlsx'
export default {
data(){
return{
outputs:[]
}
},
methods:{
readExcel (e) {
let that = this
const files = e.target.files
if (files.length < 1) {
return false
} else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
return false
}
const fileReader = new FileReader()
fileReader.readAsBinaryString(files[0])
fileReader.onload = (ev) => {
try {
const data = ev.target.result
const workbook = XLSX.read(data, {
type: 'binary'
}) // 读取数据
const wsname = workbook.SheetNames[0] // 取第一张表
const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) // 生成json表格内容
that.outputs = [] // 清空接收数据
for (let i = 0; i < ws.length; i++) {
that.outputs.push(ws[i])
}
console.log(that.outputs)
} catch (e) {
console.log(e)
return false
}
}
}
}
}
</script>
<style>
*{
margin: auto auto;
padding: 0;
}
.data{
width: 800px;
height: 400px;
}
</style>