在详细介绍前,先展示下效果
技术介绍
element UI 组件的el-upload和el-table
xlsx插件0.16.0版本
第一步,下载xlsx插件
npm install xlsx@0.16.0
在需要的文件中import导入“import xlsx form 'xlsx'
” 或import { read, untils } from 'xlsx'
第二步:编写导入按钮
<el-upload
class="upload-demo"
action=""
drag
ref="upload"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
:file-list="fileList"
:on-change="handleChange"
:show-file-list="false"
:auto-upload="false"
><i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip"><span style="color:red;font-weight:800;">请上传 .xls / .xlsx 格式文件</span></div>
</el-upload>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="name" label="姓名" width="180"></el-table-column>
<el-table-column prop="phone" label="手机号" width="180"></el-table-column>
</el-table>
handleChange(file) {
const _this = this
_this.tableData = []
const fileName = file.name;
console.log(fileName);
const reader = new FileReader();
//提取excel中文件内容
reader.readAsArrayBuffer(file.raw);
reader.onload = function () {
const buffer = reader.result;
const bytes = new Uint8Array(buffer);
const length = bytes.byteLength;
let binary = "";
for (let i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
const XLSX = require("xlsx"); //import xlsx from 'xlsx'
console.log(XLSX);
//转换二进制
const wb = XLSX.read(binary, {
type: "binary",
});
const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
console.log(outdata);
//这里for循环将excel表格数据转化成json数据
outdata.forEach((i) => {
let obj = {
name: i.姓名,
phone: i.手机号,
};
_this.tableData.push(obj); //此处是把数据添加到表格中
});
};
},
后续会将其赋予表单