1.引入工具库
npm install -S file-saver xlsx
npm install -D script-loader
2.Element 上传控件
<el-upload class="upload-demo" style="display: inline-block;" action="" :on-change="leading"
:show-file-list="false" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
:auto-upload="false">
<el-button type="primary" icon="el-icon-upload" circle size="mini"></el-button>
</el-upload>
limitUpload = 1 限制只能上传1个文件
accept 为默认打开的可上传的文件格式
:show-file-list="false" 不展示列表
action="" 因为导入,不用写上传路径,只用功能就可以
3. methods
leading(file, fileList) { // 导入
this.importfxx(file.raw)
},
importfxx(obj) { //导入方法
// 通过DOM取文件数据
let _this = this
let rABS = false; //是否将文件读取为二进制字符串
let f = obj
let reader = new FileReader();
//if (!FileReader.prototype.readAsBinaryString) {
FileReader.prototype.readAsBinaryString = function(f) {
let binary = "";
let rABS = false; //是否将文件读取为二进制字符串
let pt = this;
let wb; //读取完成的数据
let outdata;
let reader = new FileReader();
reader.onload = function(e) {
let bytes = new Uint8Array(reader.result);
let length = bytes.byteLength;
for (let i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
let XLSX = require('xlsx');
if (rABS) {
wb = XLSX.read(btoa(fixdata(binary)), { //手动转化
type: 'base64'
});
} else {
wb = XLSX.read(binary, {
type: 'binary'
});
}
outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
console.log(outdata )
//因为此时outdata 格式为
//[ "单位": "a",
// "测点名称": "b",
// "描述": "c",
// "测点类型": "d",
// "保留小数位": "e",
// "默认值": "f",
// "排序": "j"
//]
//以下方法可以改变为
// [
// "dataUnit": "a",
// "dataName": "b",
// "dataDesc": "c",
// "dataType": "d",
// "dataDecimals": "e",
// "defaultValue": "f",
// "dictSort": "j"
//]
//改变对象key方法
// let result = outdata.map(o=>{return{
//dataUnit:o['单位'],
//dataName:o["测点名称"],
// dataDesc:o["描述"],
//dataType:o["测点类型"],
//dataDecimals:o["保留小数位"],
// defaultValue:o["默认值"],
//dictSort:o["排序"],
// }});
//console.log(result )
}
reader.readAsArrayBuffer(f);
}
if (rABS) {
reader.readAsArrayBuffer(f);
} else {
reader.readAsBinaryString(f);
}
},