场景:公司需要批量导入Excel表格里的手机号字段
1、下载官方文件xlsx.full.min.js(dist文件夹下)引入到项目github链接
<script lang="javascript" src="./src/utils/xlsx.full.min.js"></script>
2、在页面添加input点击按钮
<input type="file" id="fileUploader" name="fileUploader" accept=".xls, .xlsx" @change="uploadFile"/>
3、封装处理文件的函数
/**
* xlsx文件转换成json数据
* @param {File} file xlsx文件
* @returns {Promise<error:string, Array>}
*/
const getExcelData = (file) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = function (e) {
const data = e.target.result;
const wb = XLSX.read(data, { type: "binary" });
const jsonData = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
resolve(jsonData);
};
reader.onerror = () => reject("错误的文件类型!");
reader.readAsBinaryString(file);
});
};
4、通过change事件获取文件(假设单个上传)
const uploadFile = async (e) => {
const file = e.target.files[0];
// 返回的sheetData格式为 [{ 用户: 张三, 投票项: xxx, 时间: '2020-10-10' }]
const sheetData = await getExcelData(file);
console.log('sheetData: ', sheetData);//ok结束了
};
结合element-plus
html部分
<el-upload
v-model:file-list="fileList"
class="upload-demo"
action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
multiple
accept=".xlsx"
:on-preview="handlePreview"
:on-success="uploadSuccess"
:limit="1"
>
<el-button type="primary">
批量导入<el-icon class="el-icon--right"><Upload /></el-icon>
</el-button>
<template #tip>
<div class="el-upload__tip"></div>
</template>
</el-upload>
js部分
// 上传成功的钩子
const uploadSuccess = async (status, uploadFile, uploadFiles) => {
// console.log(status, uploadFile, uploadFiles);
const file = uploadFile.raw;
// 返回的sheetData格式为 [{ 用户: 张三, 投票项: xxx, 时间: '2020-10-10' }]
sheetData.value = await getExcelData(file);
};