一、項(xiàng)目場景
批量數(shù)據(jù)上傳后臺(tái),需要從后臺(tái)下載一個(gè)固定格式的 Excel表格,然后在表格里面添加數(shù)據(jù),將數(shù)據(jù)格式化,再上傳給后臺(tái),后臺(tái)做解析處理,往數(shù)據(jù)庫添加數(shù)據(jù)
二、實(shí)現(xiàn)功能展示
點(diǎn)擊導(dǎo)入excel按鈕,跳轉(zhuǎn)到上傳excel功能頁面,點(diǎn)擊上傳或者是通過拖拽都能實(shí)現(xiàn)excel表格上傳
三、實(shí)現(xiàn)思路
通過Element UI的<el-dialog>
實(shí)現(xiàn)彈出層
1、excel按鈕
:isShow=isShow
是否顯示上傳文件層:onSuccess="success"
上傳成功之后的回調(diào)
2、excel上傳頁面
accept=".xlsx, .xls"
:限定文件類型beforeUpload(){}
在上傳之前做一些自己的特殊判斷,如判斷文件的大小是否大于 1 兆?若大于 1 兆則停止解析并提示錯(cuò)誤信息。
四、實(shí)現(xiàn)代碼
1、下載xlsx
excel導(dǎo)入功能需要使用npm包xlsx
,所以需要安裝**xlsx
**插件文章來源:http://www.zghlxwxcb.cn/news/detail-534579.html
npm i xlsx
2、頁面代碼
excel按鈕頁面
<template>
<div>
<el-button
type="primary"
@click="goExcel"
style="margin: 50px 50px 50px 50px"
>導(dǎo)入excel表格</el-button
>
<UploadExcel :onSuccess="success" :isShow="isShow"></UploadExcel>
</div>
</template>
<script>
import UploadExcel from "./components/UploadExcel.vue";
export default {
name: "App",
components: { UploadExcel },
data() {
return {
isShow: false,
};
},
methods: {
goExcel() {
this.isShow = true;
},
async success(data) {
// 數(shù)據(jù)庫的key為英文,我們上傳的key為中文,需要一一轉(zhuǎn)化
const userRelations = {
入職日期: "timeOfEntry",
手機(jī)號: "mobile",
姓名: "username",
轉(zhuǎn)正日期: "correctionTime",
工號: "workNumber",
};
// 將key值一一對應(yīng)
const newArr = data.results.map((item) => {
var userInfo = {};
Object.keys(item).forEach((key) => {
userInfo[userRelations[key]] = item[key];
});
return userInfo;
});
console.log(newArr);
// await importEmployee(newArr); // 調(diào)用上傳接口
this.$message("上傳文件成功");
this.isShow = false;
},
},
};
</script>
UploadExcel頁面
<template>
<el-dialog title="導(dǎo)入excel表格" :visible="isShow" @close="closeShow">
<div class="upload-excel">
<div class="btn-upload">
<el-button
:loading="loading"
size="mini"
type="primary"
@click="handleUpload"
>
點(diǎn)擊上傳
</el-button>
</div>
<input
ref="excel-upload-input"
class="excel-upload-input"
type="file"
accept=".xlsx, .xls"
@change="handleClick"
/>
<div
class="drop"
@drop="handleDrop"
@dragover="handleDragover"
@dragenter="handleDragover"
>
<i class="el-icon-upload" />
<span>將文件拖到此處</span>
</div>
</div>
</el-dialog>
</template>
<script>
import * as XLSX from "xlsx";
export default {
props: {
isShow: Boolean,
onSuccess: Function, // eslint-disable-line
},
data() {
return {
loading: false,
excelData: {
header: [],
results: [],
},
};
},
methods: {
closeShow() {
this.$parent.isShow = false;
},
// 點(diǎn)擊導(dǎo)入
handleDrop(e) {
e.stopPropagation();
e.preventDefault();
if (this.loading) return;
const files = e.dataTransfer.files;
if (files.length !== 1) {
this.$message.error("僅支持單個(gè)上傳一個(gè)文件");
return;
}
const rawFile = files[0]; // 獲取文件信息
if (!this.isExcel(rawFile)) {
//是不是excel文件
this.$message.error(
"Only supports upload .xlsx, .xls, .csv suffix files"
);
return false;
}
this.upload(rawFile);
e.stopPropagation();
e.preventDefault();
},
handleDragover(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
},
handleUpload() {
this.$refs["excel-upload-input"].click(); //觸發(fā)表單上傳事件,跳出選擇文件框
},
handleClick(e) {
const files = e.target.files;
const rawFile = files[0]; // only use files[0]
if (!rawFile) return;
this.upload(rawFile);
},
upload(rawFile) {
this.$refs["excel-upload-input"].value = null; // fix can't select the same excel
if (!this.beforeUpload) {
this.readerData(rawFile);
return;
}
const before = this.beforeUpload(rawFile); //判斷文件上傳大小
if (before) {
this.readerData(rawFile); //把excel轉(zhuǎn)化成數(shù)組
}
},
// 限定文件大小
beforeUpload(file) {
const isLt1M = file.size / 1024 / 1024 < 1;
if (isLt1M) {
return true;
}
this.$message({
message: "請不要上傳大于1M的文件",
type: "warning",
});
return false;
},
readerData(rawFile) {
this.loading = true;
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsArrayBuffer(rawFile);
//參數(shù)可以是 Blob 或者 File 對象異步結(jié)果將在onload 事件中體現(xiàn)
reader.onload = (e) => {
const data = e.target.result;
const workbook = XLSX.read(data, { type: "array" });
const firstSheetName = workbook.SheetNames[0]; // "SheetJS" 取出工作表名稱
const worksheet = workbook.Sheets[firstSheetName]; //取出工作表名稱對應(yīng)的表格數(shù)據(jù)
const header = this.getHeaderRow(worksheet); //表頭名
const results = XLSX.utils.sheet_to_json(worksheet); //輸出數(shù)據(jù),除去表頭
this.excelData.results = results;
this.excelData.header = header;
this.onSuccess && this.onSuccess(this.excelData);
this.loading = false;
resolve();
};
});
},
getHeaderRow(sheet) {
const headers = [];
const range = XLSX.utils.decode_range(sheet["!ref"]); //!ref: "A1:E21"
let C;
const R = range.s.r;
/* start in the first row */
for (C = range.s.c; C <= range.e.c; ++C) {
/* walk every column in the range */
const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })];
/* find the cell in the first row */
let hdr = "UNKNOWN " + C; // <-- replace with your desired default
if (cell && cell.t) hdr = XLSX.utils.format_cell(cell); //每個(gè)頭部名
headers.push(hdr);
}
return headers;
},
isExcel(file) {
return /\.(xlsx|xls|csv)$/.test(file.name);
},
},
};
</script>
<style scoped lang="scss">
.upload-excel {
display: flex;
justify-content: center;
// margin-top: 100px;
.excel-upload-input {
display: none;
z-index: -9999;
}
.btn-upload,
.drop {
border: 1px dashed #bbb;
width: 350px;
height: 160px;
text-align: center;
line-height: 160px;
}
.drop {
line-height: 80px;
color: #bbb;
i {
font-size: 60px;
display: block;
}
}
}
</style>
五、實(shí)現(xiàn)效果
文章來源地址http://www.zghlxwxcb.cn/news/detail-534579.html
到了這里,關(guān)于vue2 - 基于Element UI實(shí)現(xiàn)上傳Excel表單數(shù)據(jù)功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!