最近有個需求,最開始列表數(shù)據(jù)是通過新增按鈕一條條添加的,但是部分數(shù)據(jù)量可能上百條,客戶自己手選會很慢,所以產(chǎn)品經(jīng)理給了個需求要求可以通過上傳excle文件進行導(dǎo)入。
經(jīng)過網(wǎng)上查詢及涉及自己項目,實現(xiàn)了此功能。
第一步:安裝插件,我安的是0.16.0;原因是默認安裝版本編譯會有點問題,經(jīng)過搜索后發(fā)現(xiàn)安裝此版本后解決。
npm install xlsx@0.16.0 --save
第二步:vue頁面中導(dǎo)入XLSX依賴
<script>
import XLSX from 'xlsx'
</script>
第三步:頁面展示
<el-upload ref="upload" action="/" :show-file-list="false" :on-change="importExcel" :auto-upload="false">
<el-button class="d2-mt-10 d2-mb-10" size="mini" icon="el-icon-upload" @click="getCurrSiteColumn('oldSiteTableData')" type="primary">
上傳文件
</el-button>
</el-upload>
<!-- 列表展示組件 -->
<DetailTable ref="xxx" :columnData="columnData" :tableData="tableData" title="xxx列表" :edit="editUsage"/>
第四步:核心代碼js
// 上傳導(dǎo)入excle文件
async importExcel (file) {
const types = file.name.split('.')[1];
// 定義上傳文件類型
const fileType = ['xlsx', 'xls', 'csv'].some(
item => item === types
);
if (!fileType) {
ElMessageBox.alert('文件格式錯誤!請重新選擇');
return;
}
// 執(zhí)行處理excle文件內(nèi)容
await this.file2Xce(file).then(tab => {
if (tab && tab.length > 0) {
console.log('tab~~~', tab)
this.xlscList = [];
tab[0].sheet.forEach(item => {
for (const it of this.oldSiteColumnData) {
// 標題屬性切換,只對符合條件的標題進行轉(zhuǎn)換
if (Object.keys(item).includes(it.label)) {
item[it.prop] = item[it.label]
delete item[it.label]
}
}
this.xlscList.push(item)
});
console.log('this.xlscList~~~~~', this.xlscList);
if (this.xlscList.length) {
// 將轉(zhuǎn)換后的數(shù)據(jù)返回給頁面;此處的this[this.siteColumn],其實就是頁面中的tableData
this[this.column] = this.xlscList
console.log('當前更新的已有列表信息', this[this.column]);
}
}
});
},
// 獲取 excel 文件內(nèi)容
async file2Xce(file) {
debugger
return new Promise(function(resolve, reject) {
const reader = new FileReader();
reader.onload = function(e) {
const data = e.target.result;
this.wb = XLSX.read(data, {
type: 'binary'
});
const result = [];
this.wb.SheetNames.forEach(sheetName => {
result.push({
sheetName: sheetName,
// 調(diào)用:sheet_to_json 方法,將文件內(nèi)容解析成 json 格式
sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
});
});
console.log('result~~~~~~~~', result);
resolve(result);
};
debugger
reader.readAsBinaryString(file.raw);
});
}
上傳的文件內(nèi)容與拿到那數(shù)據(jù)內(nèi)容如下:可以看到是正好是能對應(yīng)上。
文章來源:http://www.zghlxwxcb.cn/news/detail-570462.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-570462.html
到了這里,關(guān)于vue純前端導(dǎo)入excel,獲取excel的表格數(shù)據(jù)渲染el-table的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!