updateFile(e) {
let _this = this;
let files = e.target.files;
let fileReader = new FileReader();
fileReader.onload = function(ev) {
try {
let data = ev.target.result;
let workbook = XLSX.read(data, { type: "binary" }); // 以二进制流方式读取获得整份excel表格对象
let sheetName = workbook.Sheets[workbook.SheetNames[0]]; // 这里咱们只读取第一张表,获取表名(如Sheet1)
_this.excelData = XLSX.utils.sheet_to_json(sheetName, {
header: "A",
raw: true,
defval: " " // 意思是从头开始匹配,如遇到空格,将跳过执行,并替换为" "字符串。
});
console.log(_this.excelData) // excelData在data()中声明的变量, _this.excelData就是咱们熟悉的数组数据了。
} catch (e) {
return _this.$message.error("文件类型不正确!");
}
};
// fileReader.readAsBinaryString(files[0]); // 将文件读取为二进制字符串展现在页面
}
复制代码
getExcelKeys() {
let row = this.totalForm.currentList[0];
for (let key in row) {
this.excelKey.push({
key,
value: row[key]
});
}
console.log('this.excelKey===>', this.excelKey)
this.excelData.splice(0, 1); // 删除表头
}
复制代码
这时咱们拿到了excelKey,它是excel的列与表头的对应关系key/value。 es6
getCurrentKey(name) {
let key;
this.excelKey.forEach(item => {
if (item.value === name) {
key = item.key;
}
});
return key;
}
复制代码
getTotalMoney() {
let totalMoney = 0;
let key = this.getCurrentKey("金额");
this.excelData.forEach(item => {
totalMoney = totalMoney + item[key];
});
this.totalMoney = parseInt(totalMoney);
}
复制代码
getCurrentTotalMoney() {
let keyA = this.getCurrentKey("月份");
let keyB = this.getCurrentKey("金额");
let currentTotalMoney = 0;
this.currentList = this.excelData.filter(item => item[keyA] === month) // month这里定义为想要获取数据的月份
this.currentList.forEach(item => {
currentTotalMoney = currentTotalMoney + item[keyB];
});
this.currentTotalMoney = parseInt(currentTotalMoney);
}
复制代码
getTotalMoneyArr() {
let keyA = this.getCurrentKey("年份");
let keyB = this.getCurrentKey("月份");
let keyC = this.getCurrentKey("金额");
this.currentList = this.excelData.filter(item => item[keyA] === '2018') // 获得2018年全部的数据
let data = [], // 2018年1~12月每月的收入总额
let obj = {};
this.currentList.forEach(item => { // 下面有详细介绍
if (obj[item[keyB]]) {
obj[item[keyB]] = obj[item[keyB]] + item[keyC];
} else {
obj[item[keyB]] = item[keyC];
}
});
for (let key in obj) { // 对象属性的遍历
if (key.trim() !== "") { // key.trim() === '' => 是为了排除excel表中空数据的状况
data.push({
name: key,
value: parseInt(obj[key])
});
}
}
}
复制代码
es6多个数组的去重
[...new Set(arr1.concat(arr2))] 或者
Array.from(new Set(arr1.concat(arr2)))
在es5中传统的作法是先遍历arr1,而后去到arr2查找是否存在该元素在push到新数组中,这里咱们介绍一下利用对象的方法:
this.currentList.forEach(item => { // 这是上面咱们对每月金额求和方法
if (obj[item[keyB]]) { // 这个对月份进行去重,把月份做为obj的key值,判断key是否存在。
obj[item[keyB]] = obj[item[keyB]] + item[keyC]; // 对应的value值为金额的求和
} else {
obj[item[keyB]] = item[keyC];
}
});
复制代码