我想實現讀取一個本地的xlsx文件(task_list.xlsx)而後顯示在網頁上, 一開始選擇的方法是建個express server, 經過發送axios請求來實現, 可是以爲只是讀取一個本地文件還要搞個server太複雜了, 最終仍是經過"xlsx"模塊 + axios實現了讀取本地文件, 無需後端, 步驟以下:vue
1.經過vue-cli新建項目:
ios
2.編寫分析excel workbook的腳本
/src/scripts/read_xlsx.jsgit
const XLSX = require('xlsx') //將行,列轉換 function transformSheets(sheets) { var content = [] var content1 = [] var tmplist = [] for (let key in sheets){ //讀出來的workbook數據很難讀,轉換爲json格式,參考https://github.com/SheetJS/js-xlsx#utility-functions tmplist.push(XLSX.utils.sheet_to_json(sheets[key]).length) content1.push(XLSX.utils.sheet_to_json(sheets[key])) } var maxLength = Math.max.apply(Math, tmplist) //進行行列轉換 for (let y in [...Array(maxLength)]){ content.push([]) for (let x in [...Array(tmplist.length)]) { try { for (let z in content1[x][y]){ content[y].push(content1[x][y][z]) } } catch (error) { content[y].push(' ') } } } content.unshift([]) for (let key in sheets){ content[0].push(key) } return content } export {transformSheets as default}
3.新建一個組件
/src/components/task_list.vuegithub
<template> <div class="task-list"> <p v-if="err!==''">{{err}}</p> <!-- 用來顯示報錯 --> <table style="margin:0 auto;" v-if="content!==''"> <!-- 設置居中,若是沒獲取到內容則不顯示 --> <tr><th v-for="h in content[0]" :key="h.id">{{h}}</th></tr> <!-- 循環讀取數據並顯示 --> <tr v-for="row in content.slice(1,)" :key=row.id> <td v-for="item in row" :key=item.id>{{item}}</td> </tr> </table> </div> </template> <script> import axios from 'axios' import XLSX from 'xlsx' import transformSheets from '../scripts/read_xlsx' //導入轉制函數 export default { name: 'TaskList', data: function () { return { content: '', //初始化數據 err: '' } }, created() { var url = "/task_list.xlsx" //放在public目錄下的文件能夠直接訪問 //讀取二進制excel文件,參考https://github.com/SheetJS/js-xlsx#utility-functions axios.get(url, {responseType:'arraybuffer'}) .then((res) => { var data = new Uint8Array(res.data) var wb = XLSX.read(data, {type:"array"}) var sheets = wb.Sheets this.content = transformSheets(sheets) }).catch( err =>{ this.err = err }) } }
大功告成,編譯而後部署到服務器吧vue-cli
npm run build
部署就不詳述了,把dist目錄丟到服務器上就行.
效果就是這樣,編程新手,就這個東西斷斷續續搞了快一週了...express
github地址 https://github.com/LeviDeng/t...
但願能有幫助,喜歡的給個star吧😃npm