首先安装引入xlsx
npm run install xlsx //安装
import * as XLSX from "xlsx"; //引入
<div class="xls" >
<span>导入</span>
<input
type="file"
accept=".xls,.xlsx"
class="upload-file"
ref="uploadImgBtn"
@change="Excel($event)" />
</div>
// 导入
function Excel(w){
const files = w.target.files
if (files.length <= 0) {
return false
} else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
return false
}
// 读取表格
const fileReader = new FileReader()
fileReader.onload = ev => {
const workbook = XLSX.read(ev.target.result, {
type: "binary"
})
const wsname = workbook.SheetNames[0]
const xl = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])
dealExcel(xl) //...对数据进行自己需要的操作
tableData.value = xl
}
fileReader.readAsBinaryString(files[0])
}
function transitionExcel(xl){
let keymap = { // 根据所要导入的文件转换开头
"姓名": "name",
"联系方式": 'tel',
"性别":'男'
"备注":'remark'
}
ws.forEach(sourceObj => {
Object.keys(sourceObj).map(keys => {
let newKey = keymap[keys]
if (newKey) {
sourceObj[newKey] = sourceObj[keys]
delete sourceObj[keys]
}
})
})
tableData.value = ws
}
.xls { //可改变HTML input上传文件标签样式
width: 60px;
height: 32px;
margin-right: 10px;
background: rgba(126, 156, 255);
border-radius: 5px;
font-weight: 400;
line-height: 24px;
color: rgba(255, 255, 255, 1);
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
user-select: none;
}
.xls>input {
position: absolute;
width: 80px;
height: 52px;
opacity: 0;
cursor: pointer;
z-index: 99;
}