vue前端導入excel表格並解析表格內數據
需求
- 用戶需要輸入一系列的ip
- 如果ip過多手動輸入太麻煩,所以用戶可以把ip寫入Excel表格,然后導入
- 為防止用戶創建Excel表格時格式錯誤,所以我們提供一個模板供下載
插件
npm install xlsx --save
代碼
- HTML代碼(用的是element-ui,不同前端框架獲取到的對象可能不同,因此,需注意尋找自己獲取到的對象中的正確File對象)
<el-upload class="upload-demo" ref="upload" action="" :auto-upload="false" :file-list="fileList" :on-change="handleChange" multiple :show-file-list="false" > <el-button type="text">點擊上傳</el-button> </el-upload>
- data
data(){ return{ fileList:[], file:"" } }
- js代碼
handleChange(file,fileList){ this.fileList = [fileList[fileList.length - 1]]; // 只能上傳一個Excel,重復上傳會覆蓋之前的 this.file = file.raw; let reader = new FileReader() let _this = this reader.readAsArrayBuffer(this.file) reader.onload = function () { let buffer = reader.result let bytes = new Uint8Array(buffer) let length = bytes.byteLength let binary = '' for (let i = 0; i < length; i++) { binary += String.fromCharCode(bytes[i]) } let XLSX = require('xlsx') let wb = XLSX.read(binary, { type: 'binary' }) let outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]) console.log(outdata) }
- 打印出的outdata
- 導入的表格內容
轉自:https://www.tqwba.com/x_d/jishu/354134.html