vue中使用excel導入導出

一、在vue中使用導入導出,須要下載3個依賴包和2個js包:javascript

 使用npm安裝:css

 npm install -S file-saver xlsx(這裏其實安裝了2個依賴)

 npm install -D script-loader

使用yarn安裝:vue

yarn add file-saver

yarn add xlsx

yarn add script-loader --dev

二、在src目錄下新建一個excel文件夾引入Blob.js和expor2Excal.jsjava

三、在main.js中全局引入:webpack

import Blob from './excel/Blob.js'
import Export2Excel from './excel/Export2Excel.js'

四、webpack.base.conf.js作以下修改:web

 

resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
      'scss_vars': '@/styles/vars.scss',
      'excel': path.resolve(__dirname, '../src/excel'),//新增長一行
    }
  },

五、在頁面中導出的時候調用outExe:npm

// 導出
            outExe() {
                this.$confirm('此操做將導出excel文件, 是否繼續?', '提示', {
                    confirmButtonText: '肯定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.excelData = this.dataList //你要導出的數據list。
                    this.export2Excel()
                }).catch(() => {
                
                });
            },
            export2Excel() {
                var that = this;
                require.ensure([], () => {
                    const { export_json_to_excel } = require('../../excel/Export2Excel'); //這裏必須使用絕對路徑
                    const tHeader = ['id','withNum', 'userId', 'name','amount','status','amountIn','amountSuccess','createTime']; // 導出的表頭名
                    const filterVal = ['id','withNum','userId', 'name','amount','status','amountIn','amountSuccess','createTime']; // 導出的表頭字段名
                    const list = that.excelData;
                    const data = that.formatJson(filterVal, list);
                    let time1,time2 = '';
                    if(this.start !== '') {
                        time1 = that.moment(that.start).format('YYYY-MM-DD')
                    }
                    if(this.end !== '') {
                        time2 = that.moment(that.end).format('YYYY-MM-DD')
                    }
                    export_json_to_excel(tHeader, data, `[${time1}-${time2}]提現管理excel`);// 導出的表格名稱,根據須要本身命名
                })
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => v[j]))
            }

六、在頁面中導入的時候調用:json

// 導入
<a href="javascript:;" class="file">導入表格
<input id="upload" type="file" @change="importfxx(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
</a>

importfxx(obj) { let _this = this; let inputDOM = this.$refs.inputer; // 經過DOM取文件數據 this.file = event.currentTarget.files[0]; var rABS = false; //是否將文件讀取爲二進制字符串 var f = this.file; var reader = new FileReader(); //if (!FileReader.prototype.readAsBinaryString) { FileReader.prototype.readAsBinaryString = function(f) { var binary = ""; var rABS = false; //是否將文件讀取爲二進制字符串 var pt = this; var wb; //讀取完成的數據 var outdata; var reader = new FileReader(); reader.onload = function(e) { var bytes = new Uint8Array(reader.result); var length = bytes.byteLength; for(var i = 0; i < length; i++) { binary += String.fromCharCode(bytes[i]); } var XLSX = require('xlsx'); if(rABS) { wb = XLSX.read(btoa(fixdata(binary)), { //手動轉化 type: 'base64' }); } else { wb = XLSX.read(binary, { type: 'binary' }); } outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);//outdata就是你想要的東西 this.da = [...outdata] let arr = [] this.da.map(v => { let obj = {} obj.id = v.id obj.status = v.status arr.push(obj) }) console.log(arr) let para = { //withList: JSON.stringify(this.da) withList: arr } _this.$message({ message: '請耐心等待導入成功', type: 'success' }); withImport(para).then(res => { window.location.reload() }) } reader.readAsArrayBuffer(f); } if(rABS) { reader.readAsArrayBuffer(f); } else { reader.readAsBinaryString(f); } },
相關文章
相關標籤/搜索