此处为须要插件
- xlsx
- 此处为 vue 父组件引入办法
// import excel from "./components/upload-excel.vue";
// <excel v-on:getResult="updateExcel"></excel>
此处为编辑好的 vue 组件
<template>
<div>
<span>
<input class="input-file" hidden="hidden" type="file" @change="exportData"
accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
<a-button class="m-x-10" type="primary" @click="btnClick">
导入
</a-button>
</span>
</div>
</template>
<script>
// 图标组件要独自引入
import {defineComponent, reactive, onMounted, toRefs, computed} from "vue";
// import {UpOutlined, DownOutlined} from '@ant-design/icons-vue';
// import {message} from 'ant-design-vue';
// import {useStore} from 'vuex';
// import {useApi} from '@/common/utils/api';
export default defineComponent({components: {},
setup(props, context) {const data = reactive({});
const methods = {btnClick() {document.querySelector(".input-file").click();
//
},
exportData(event) {if (!event.currentTarget.files.length) {return;}
// 拿取文件对象
const f = event.currentTarget.files[0];
// 用 FileReader 来读取
const reader = new FileReader();
// 重写 FileReader 上的 readAsBinaryString 办法
FileReader.prototype.readAsBinaryString = function (f) {
let binary = "";
let wb; // 读取实现的数据
let outdata; // 你须要的数据
const reader = new FileReader();
reader.onload = function (e) {
// 读取成 Uint8Array,再转换为 Unicode 编码(Unicode 占两个字节)const bytes = new Uint8Array(reader.result);
const length = bytes.byteLength;
for (let i = 0; i < length; i++) {binary += String.fromCharCode(bytes[i]);
}
// 接下来就是 xlsx 了,具体可看 api
// 上行必须加上,否者报错
// eslint-disable-next-line @typescript-eslint/no-var-requires
const XLSX = require("xlsx");
wb = XLSX.read(binary, {type: "binary",});
outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
// 自定义办法向父组件传递数据
// console.log("outdata =" + JSON.stringify(outdata));
// console.log(outdata);
context.emit("getResult", outdata);
};
reader.readAsArrayBuffer(f);
};
reader.readAsBinaryString(f);
},
};
return {...toRefs(data),
...methods,
};
},
});
</script>