1.安装插件npm install xlsx --save
2.封装组件
<template>
<span class="content" @click="selectExcel">
<input
id="uploadFile"
class="input-file"
type="file"
@change="exportData"
accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
/>
{{ title }}
</span>
</template>
<script>
import XLSX from "xlsx";
export default {
name: "importExcel",
props: {
title: {
type: String,
default: "导入表格",
},
},
methods: {
selectExcel() {
document.getElementById("uploadFile").click();
},
exportData(event) {
if (!event.currentTarget.files.length) {
return;
}
const that = this;
// 拿取文件对象
let f = event.currentTarget.files[0];
// 用FileReader来读取
let reader = new FileReader();
// 重写FileReader上的readAsBinaryString方法
const rABS = true;
reader.onload = (e) => {
let dataResult = e.target.result;
if (!rABS) dataResult = new Uint8Array(dataResult);
const workbook = XLSX.read(dataResult, {
type: rABS ? "binary" : "array",
});
// 假设我们的数据在第一个标签
const firstWorksheet = workbook.Sheets[workbook.SheetNames[0]];
// XLSX自带了一个工具把导入的数据转成json
const jsonArr = XLSX.utils.sheet_to_json(firstWorksheet, { header: 1 });
// 通过自定义的方法处理Json,比如加入state来展示
that.$emit("getResult", jsonArr);
document.getElementById("uploadFile").value = null;
};
if (rABS) reader.readAsBinaryString(f);
else reader.readAsArrayBuffer(f);
return false;
},
},
};
</script>
<style scoped>
.input-file {
display: none;
}
.content {
margin-right: 5px;
}
</style>
3.父组件调用
<template>
<div >
<UpExcel title="上传" @getResult="getExcelData"></UpExcel>
</div>
</template>
<script>
import UpExcel from "./components/upExcel.vue";
export default {
name: "App",
components: {
UpExcel,
},
data() {
return {
};
},
methods: {
getExcelData(data) {
// data为读取Excel的原始数据,这里可以对Excel进行格式校验和数据格式化处理
console.log(data);
},
},
};
</script>
网友评论