vue 實(shí)現(xiàn)讀取excel內(nèi)容剔猿,并且以table格式展示
查了很多網(wǎng)上的方法视译,但是都沒有用ant design來(lái)做的,因?yàn)楣居玫膉eccg Boot框架艳馒,沒有辦法憎亚,自己來(lái)弄吧~~
先看最后效果
效果圖.PNG
下面要上代碼了
-首先第一步,需要下載解析excel的插件
// 直接 npm 安裝即可,不用引用
npm install xlsx
-第二步弄慰,HTML布局
<li>
<div>選擇文件:</div>
<a-upload
name="file"
:multiple="false"
:action='clAction'
@change="uploadFilecl"
:file-list="fileListcl"
:before-upload="beforeUploadcl"
>
<a-button>上傳產(chǎn)量</a-button>
</a-upload>
</li>
<a-table :columns="columns" :data-source="tableData" style="margin-top:45px" :scroll="{ x: 1000}">
<a slot="name" slot-scope="text">{{ text }}</a>
</a-table>
-js
data() {
return {
clAction:'https://www.mocky.io/v2/5cc8019d300000980a055e76',//后臺(tái)上傳地址
fileListcl:null,//顯示列表
columns:[],//table頭
tableData:[]//table內(nèi)容
};
},
methods: {
beforeUploadcl(file){//上傳之前回調(diào)第美,判斷上傳類型
const isJpgOrPng = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
if (!isJpgOrPng) {
this.$message.error('請(qǐng)選擇xlsx類型文件');
this.fileListcl = []
}
return isJpgOrPng;
},
uploadFilecl(info){//上傳文件
//ant design 框架中此回調(diào)會(huì)運(yùn)行三次,上傳中陆爽、完成什往、失敗都會(huì)調(diào)用這個(gè)函數(shù)。
if(info.event){//只判斷是完成的時(shí)候
this.importfile(info.file)//核心函數(shù)
}
let fileList = [...info.fileList];
this.fileListcl = fileList.slice(-1);
if (info.file.status === 'uploading') {
this.loading = true;
return;
}
if (info.file.status === 'done') {
//上傳成功慌闭,可以做接下來(lái)的操作
}
},
//核心函數(shù)
importfile (obj) {
const _this = this
const reader = new FileReader()
_this.tableData = []
_this.columns = []
reader.readAsArrayBuffer(obj.originFileObj)//需要傳blob類型
reader.onload = function () {
const buffer = reader.result
const bytes = new Uint8Array(buffer)
const length = bytes.byteLength
let binary = ''
for (let i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i])
}
const XLSX = require('xlsx')//引用
const wb = XLSX.read(binary, {
type: 'binary'
})
const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
// console.log(outdata)别威,此為取到的excel中內(nèi)容,然后就可以自己改數(shù)據(jù)驴剔,畫頁(yè)面啦~
let tableheader = outdata[0]
for(let val in tableheader){
_this.columns.push({
title: val,
dataIndex: val,
key: val,
})
}
outdata.forEach((v,i)=>{
v={...v,"key":i}
})
_this.tableData = outdata
}
},
}