1 解析excel的公共方法
//解析文件内容
export const fileAnalysis = (e) => {
return new Promise((resolve, reject) => {
this.fileTemp = e.target.files[0];
if(this.fileTemp){
if((this.fileTemp.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|| (this.fileTemp.type == 'application/vnd.ms-excel') || (this.fileTemp.type == '')){
let obj = this.fileTemp;
let _this = this;
//let inputDOM = this.$refs.inputer;
// 通过DOM取文件数据
this.file = event.currentTarget.files[0];
let rABS = false; //是否将文件读取为二进制字符串
let f = this.file;
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]);
}
//此处引入,用于解析excel
let XLSX = require("xlsx");
if (rABS) {
wb = XLSX.read(btoa(fixdata(binary)), {
//手动转化
type: "base64"
});
} else {
wb = XLSX.read(binary, {
type: "binary",
cellDates: true,
});
}
outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
//outdata就是读取的数据(不包含标题行即表头,表头会作为对象的下标)
//此处可对数据进行处理
resolve(outdata);
};
reader.readAsArrayBuffer(f);
};
if (rABS) {
reader.readAsArrayBuffer(f);
} else {
reader.readAsBinaryString(f);
}
} else {
Vue.prototype.$message({
type:'warning',
message:'附件格式错误,请删除后重新上传!'
});
}
} else {
Vue.prototype.$message({
type: 'warning',
});
}
});
}
2 引用方法
//选中文件
async selectedFile(e) {
await fileAnalysis(e).then((res) => {
console.log(res)
let dataNum = 0;
let dataList = this.tabData.dataDetail;
this.tabData.dataDetail = [];
res.map((v) => {
console.log(v)
});
});
},
3 说明
打印的res是一个List<Map<String, Object>>集合, excel中一行数据为一个Map,Map的Key值就是excel的标题,多行数据组成一个List集合,案需求处理即可