鍍金池/ 問答/HTML/ 已有基于vue的讀取excel 的網(wǎng)頁,如何二次開發(fā)不用點(diǎn)擊"導(dǎo)入文件

已有基于vue的讀取excel 的網(wǎng)頁,如何二次開發(fā)不用點(diǎn)擊"導(dǎo)入文件",自動(dòng)導(dǎo)入excel

現(xiàn)在我在github上找到一個(gè)vue的純前端處理excel的項(xiàng)目,部署好之后,點(diǎn)擊導(dǎo)入文件即可在網(wǎng)頁上顯示excel表格里的內(nèi)容,現(xiàn)在我是有一個(gè)excel放在這個(gè)項(xiàng)目的根目錄下,我想每次打開就直接能夠讀取這個(gè)excel文件,而不需要再點(diǎn)擊導(dǎo)入再選擇這個(gè)文件才可以顯示,請(qǐng)問如何修改?


代碼如下

<template>
  <div class="index" v-loading.fullscreen.lock="fullscreenLoading" element-loading-text="拼命加載中...">
    <input type="file" @change="importFile(this)" id="imFile" style="display: none"
           accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
    <a id="downlink"></a>
    <el-button class="button" @click="uploadFile()">導(dǎo)入</el-button>
    <el-button class="button" @click="downloadFile(excelData)">導(dǎo)出</el-button>
    <!--錯(cuò)誤信息提示-->
    <el-dialog title="提示" v-model="errorDialog" size="tiny">
      <span>{{errorMsg}}</span>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="errorDialog=false">確認(rèn)</el-button>
        </span>
    </el-dialog>
    <!--展示導(dǎo)入信息-->
    <el-table :data="excelData" tooltip-effect="dark">
      <el-table-column label="時(shí)間" prop="time" show-overflow-tooltip></el-table-column>
      <el-table-column label="酒精度1" prop="alcoholone" show-overflow-tooltip></el-table-column>
      <el-table-column label="酒精度2" prop="alcoholtwo" show-overflow-tooltip></el-table-column>
      <el-table-column label="CO2濃度" prop="CO2" show-overflow-tooltip></el-table-column>
    </el-table>
  </div>
</template>

<script>
  var XLSX = require('xlsx')
  export default {
    name: 'Index',
    data () {
      return {
        fullscreenLoading: false, // 加載中
        imFile: '', // 導(dǎo)入文件el
        outFile: '',  // 導(dǎo)出文件el
        errorDialog: false, // 錯(cuò)誤信息彈窗
        errorMsg: '' // 錯(cuò)誤信息內(nèi)容
        // excelData: [  // 測(cè)試數(shù)據(jù)
        //   {
        //     name: '紅燒魚', size: '大', taste: '微辣', price: '40', remain: '100'
        //   },
        //   {
        //     name: '麻辣小龍蝦', size: '大', taste: '麻辣', price: '138', remain: '200'
        //   },
        //   {
        //     name: '清蒸小龍蝦', size: '大', taste: '清淡', price: '138', remain: '200'
        //   },
        //   {
        //     name: '香辣小龍蝦', size: '大', taste: '特辣', price: '138', remain: '200'
        //   },
        //   {
        //     name: '十三香小龍蝦', size: '大', taste: '中辣', price: '138', remain: '108'
        //   },
        //   {
        //     name: '蒜蓉小龍蝦', size: '大', taste: '中辣', price: '138', remain: '100'
        //   },
        //   {
        //     name: '涼拌牛肉', size: '中', taste: '中辣', price: '48', remain: '60'
        //   },
        //   {
        //     name: '蝦仁壽司', size: '大', taste: '清淡', price: '29', remain: '無限'
        //   },
        //   {
        //     name: '海苔壽司', size: '大', taste: '微辣', price: '26', remain: '無限'
        //   },
        //   {
        //     name: '金針菇壽司', size: '大', taste: '清淡', price: '23', remain: '無限'
        //   },
        //   {
        //     name: '泡菜壽司', size: '大', taste: '微辣', price: '24', remain: '無限'
        //   },
        //   {
        //     name: '鰻魚壽司', size: '大', taste: '清淡', price: '28', remain: '無限'
        //   },
        //   {
        //     name: '肉松壽司', size: '大', taste: '清淡', price: '22', remain: '無限'
        //   },
        //   {
        //     name: '三文魚壽司', size: '大', taste: '清淡', price: '30', remain: '無限'
        //   },
        //   {
        //     name: '蛋黃壽司', size: '大', taste: '清淡', price: '20', remain: '無限'
        //   }
        // ]
      }
    },
    mounted () {
      this.imFile = document.getElementById('imFile')
      this.outFile = document.getElementById('downlink')
    },
    methods: {
      uploadFile: function () { // 按鈕導(dǎo)入
        this.imFile.click()
        console.log(this.imFile)
      },
      downloadFile: function (rs) { // 按鈕導(dǎo)出
        let data = [{}]
        for (let k in rs[0]) {
          data[0][k] = k
        }
        data = data.concat(rs)
        this.downloadExl(data, '菜單')
      },
      importFile: function () { // 導(dǎo)入excel
        this.fullscreenLoading = true
        console.log(this.imFile)
        let obj = this.imFile
        console.log(obj.files[0])
        if (!obj.files) {
          this.fullscreenLoading = false
          return
        }
        var f = obj.files[0]
        var reader = new FileReader()
        let $t = this
        reader.onload = function (e) {
          var data = e.target.result
          if ($t.rABS) {
            $t.wb = XLSX.read(btoa(this.fixdata(data)), {  // 手動(dòng)轉(zhuǎn)化
              type: 'base64'
            })
          } else {
            $t.wb = XLSX.read(data, {
              type: 'binary'
            })
          }
          let json = XLSX.utils.sheet_to_json($t.wb.Sheets[$t.wb.SheetNames[0]])
          console.log(typeof json)
          $t.dealFile($t.analyzeData(json)) // analyzeData: 解析導(dǎo)入數(shù)據(jù)
        }
        if (this.rABS) {
          reader.readAsArrayBuffer(f)
        } else {
          reader.readAsBinaryString(f)
        }
      },
      downloadExl: function (json, downName, type) {  // 導(dǎo)出到excel
        let keyMap = [] // 獲取鍵
        for (let k in json[0]) {
          keyMap.push(k)
        }
        console.info('keyMap', keyMap, json)
        let tmpdata = [] // 用來保存轉(zhuǎn)換好的json
        json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
          v: v[k],
          position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
        }))).reduce((prev, next) => prev.concat(next)).forEach(function (v) {
          tmpdata[v.position] = {
            v: v.v
          }
        })
        let outputPos = Object.keys(tmpdata)  // 設(shè)置區(qū)域,比如表格從A1到D10
        let tmpWB = {
          SheetNames: ['mySheet'], // 保存的表標(biāo)題
          Sheets: {
            'mySheet': Object.assign({},
              tmpdata, // 內(nèi)容
              {
                '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] // 設(shè)置填充區(qū)域
              })
          }
        }
        let tmpDown = new Blob([this.s2ab(XLSX.write(tmpWB,
          {bookType: (type === undefined ? 'xlsx' : type), bookSST: false, type: 'binary'} // 這里的數(shù)據(jù)是用來定義導(dǎo)出的格式類型
        ))], {
          type: ''
        })  // 創(chuàng)建二進(jìn)制對(duì)象寫入轉(zhuǎn)換好的字節(jié)流
        var href = URL.createObjectURL(tmpDown)  // 創(chuàng)建對(duì)象超鏈接
        this.outFile.download = downName + '.xlsx'  // 下載名稱
        this.outFile.href = href  // 綁定a標(biāo)簽
        this.outFile.click()  // 模擬點(diǎn)擊實(shí)現(xiàn)下載
        setTimeout(function () {  // 延時(shí)釋放
          URL.revokeObjectURL(tmpDown) // 用URL.revokeObjectURL()來釋放這個(gè)object URL
        }, 100)
      },
      analyzeData: function (data) {  // 此處可以解析導(dǎo)入數(shù)據(jù)
        return data
      },
      dealFile: function (data) {   // 處理導(dǎo)入的數(shù)據(jù)
        console.log(data)
        this.imFile.value = ''
        this.fullscreenLoading = false
        if (data.length <= 0) {
          this.errorDialog = true
          this.errorMsg = '請(qǐng)導(dǎo)入正確信息'
        } else {
          this.excelData = data
        }
      },
      s2ab: function (s) { // 字符串轉(zhuǎn)字符流
        var buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i !== s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xFF
        }
        return buf
      },
      getCharCol: function (n) { // 將指定的自然數(shù)轉(zhuǎn)換為26進(jìn)制表示。映射關(guān)系:[0-25] -> [A-Z]。
        let s = ''
        let m = 0
        while (n > 0) {
          m = n % 26 + 1
          s = String.fromCharCode(m + 64) + s
          n = (n - m) / 26
        }
        return s
      },
      fixdata: function (data) {  // 文件流轉(zhuǎn)BinaryString
        var o = ''
        var l = 0
        var w = 10240
        for (; l < data.byteLength / w; ++l) {
          o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)))
        }
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
        return o
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
  .el-table th>.cell {
    text-align: center;
  }
  .button {
    margin-bottom: 20px;
  }
</style>
回答
編輯回答
陌南塵

不通過 input標(biāo)簽上傳文件,前端應(yīng)該是不能讀取excel文件的。
你通過XLSX.js解析excel文件,得到的不就是一個(gè)數(shù)組嘛。所以剛開始你沒必要讀取excel文件,可以事先把這個(gè)excel文件先轉(zhuǎn)成數(shù)組,直接使用。

2017年4月20日 14:27
編輯回答
笑忘初

這個(gè)好像不行,你需要使用input才可以

2018年1月25日 13:41