不想码字,还是直接上代码好了
需要有xlsl插件 可直接npm i xlsx
<template>
<div>
<el-button type="primary" size="mini" style="margin-right: 10px" @click.stop="importExcel">批量导入</el-button>
<input type="file" ref="upload" accept=".xls, .xlsx" style="display: none" />
</div>
</template>
<script>
import * as XLSX from "xlsx/xlsx.mjs";
export default {
mounted() {
this.$refs.upload.addEventListener("change", (e) => {
this.readExcel(e);
});
},
methods: {
importExcel() {
this.$refs.upload.dispatchEvent(new MouseEvent("click"));
},
readExcel(e) {
const files = e.target.files;
if (files.length <= 0) {
return false;
} else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
this.$Message.error("上传格式不正确,请上传xls或者xlsx格式");
return false;
}
const fileReader = new FileReader();
fileReader.onload = (ev) => {
try {
const data = ev.target.result;
const workbook = XLSX.read(data, { type: "binary" });
const wsname = workbook.SheetNames[0];
const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
ws.forEach(item => { item.date = this.dateFormat(item.date) })
console.log(ws);
// this.$emit("getExcel", this.changeWS(ws));
} catch (e) {
return false;
}
};
fileReader.readAsBinaryString(files[0]);
},
dateFormat(numb, format = "-") {
const time = new Date(
(numb - 25567) * 24 * 3600000 -
5 * 60 * 1000 -
43 * 1000 -
24 * 3600000 -
8 * 3600000
);
time.setYear(time.getFullYear());
const year = time.getFullYear() + "";
const month = time.getMonth() + 1 + "";
const date = time.getDate() + "";
if (format && format.length === 1) {
return year + format + month + format + date;
}
return (
year +
(month < 10 ? "0" + month : month) +
(date < 10 ? "0" + date : date)
);
},
},
};
</script>
修改上传的日期
上传文件内容
效果使用前/后
至于转换关于包含日期时间的 需要其他的方法,恭请期待下一篇博客