<input id="upload" type="file" @change="importfxx()" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
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(); 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 = _this.dateTransition(outdata); } reader.readAsArrayBuffer(f); } if(rABS) { reader.readAsArrayBuffer(f); } else { reader.readAsBinaryString(f); } };
// 將對應的中文key轉化爲本身想要的英文key dateTransition(outdata) { let list = []; var obj = {}; for(var i = 0; i < outdata.length; i++) { obj = {}; for(var key in outdata[i]) { if(key == '工號') { obj['jobNumber'] = outdata[i][key]; } else if(key == '姓名') { obj['name'] = outdata[i][key]; } else if(key == '部門') { obj['department'] = outdata[i][key];
}
}
list.push(obj); } return list; };
例如:現有一張excel表格須要導入。javascript
導入後,獲取到的outdata爲vue
outdata = [
{
"姓名": "張三",
"工號": "1001",
"部門": "技術部"
},
{
"姓名": "李四",
"工號": "1002",
"部門": "技術部"
},
];java
這裏獲取到outdata的json格式的key值對應的是導入的excel表格中的表頭名稱,每每都是中文的,要想把中文key轉化爲本身想要的英文key就須要用到dateTransition函數了。npm
經過dateTransition函數轉化後對應的importList變爲json
importList = [
{
"name": "張三",
"jobNumber": "1001",
"department": "技術部"
},
{
"name": "李四",
"jobNumber": "1002",
"department": "技術部"
}
];數組
<input type="button" value="導出" @click="exportExcel" />
exportExcel() { //兼容ie10哦! require.ensure([], () => { const { export_json_to_excel } = require('../../vendor/Export2Excel'); //引入文件 const tHeader = ['姓名', '工號', '部門']; //將對應的屬性名轉換成中文 //const tHeader = []; const filterVal = ['name', 'jobNumber', 'department'];//table表格中對應的屬性名 const list = exportData; //想要導出的數據 const data = this.formatJson(filterVal, list); export_json_to_excel(tHeader, data, '列表excel'); }) },
formatJson(filterVal, jsonData) { return jsonData.map(v => filterVal.map(j => v[j])); }
這裏的exportData就是你想要導出的數組app
exportData = [
{
"name": "張三",
"jobNumber": "1001",
"department": "技術部"
},
{
"name": "李四",
"jobNumber": "1002",
"department": "技術部"
}
];函數
導出的excel表ui