新建一個js文件。vue
import Vue from 'vue'; /** * @method formatJson * @param {Array} filterVal 導出表頭的中文表頭對應的英文名稱 * 例:['name', 'age'] * @param {Array} jsonData 導出的數據 * 例:[{ * name: '張三', * age: 14 * }] * @return {Array} 組裝成須要導出的excel數據 */ let formatJson = (filterVal, jsonData) => { return jsonData.map(v => filterVal.map(j => v[j])); }; /** * @method dateTransition * @param {Array} outdata excel表導入的數據 * 例:[{ * 姓名: '張三', 年齡: 14 * }] * @param {Array} importModel excel表頭中文名稱和其對應的英文名稱 * 例:[{ * label: '姓名', * value: 'name' * },{ * label: '年齡', * value: 'age' * }] * @return {Array} 組裝成須要導入的excel數據 */ let dateTransition = (outdata, importModel) => { console.log('outdata', outdata); console.log('importModel', importModel); let importData = []; for(let item of outdata) { let obj = {}; for(let key in item) { for(let childItem of importModel) { if(key === childItem.label) { obj[childItem.value] = item[key]; break; } } } importData.push(obj); } return importData; }; /** * @method $exportExcel * @param {Array} tHeader 導出表格的中文表頭 * 例:['姓名', '年齡'] * @param {Array} filterVal 導出表頭的中文表頭對應的英文名稱 * 例:['name', 'age'] * @param {Array} exportList 導出的數據 * 例:[{ * name: '張三', * age: 14 * }] * @param {String} excelName 導出的excel表格名稱 * @return {null} 無返回值 */ Vue.prototype.$exportExcel = (tHeader, filterVal, exportList, excelName) => { require.ensure([], () => { const { export_json_to_excel } = require('@/vendor/Export2Excel'); //引入文件 tHeader.unshift('序號'); filterVal.unshift('index'); for(let i = 0;i < exportList.length;i++){ exportList[i].index=i+1+''; } const data = formatJson(filterVal, exportList); console.log('data', data); export_json_to_excel(tHeader, data, excelName); }); }; /** * @method $importExcel * @param {Object} event 文件表單觸發change事件的event對象 * @param {Array} importModel excel表頭中文名稱和其對應的英文名稱 * 例:[{ * label: '姓名', * value: 'name' * },{ * label: '年齡', * value: 'age' * }] * @return {null} 無返回值 */ // 導入 Vue.prototype.$importExcel = (event, importModel) => { return new Promise((resolve, reject) => { var f = event.currentTarget.files[0]; var rABS = false; //是否將文件讀取爲二進制字符串 var reader = new FileReader(); 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]]); let importList = dateTransition(outdata, importModel); resolve(importList); } reader.readAsArrayBuffer(f); } if(rABS) { reader.readAsArrayBuffer(f); } else { reader.readAsBinaryString(f); } }); };