Vue导入Excel文件
Survivor 人气:0以将此Excel导出为json数据为例
一、安装依赖
npm install file-saver --save npm install xlsx --save npm install script-loader --save-dev
二、template中
<span>导入表格</span> <input id="upload" type="file" @change="importfxx()" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
三、script中js代码
methods:{ // 处理导入Excel中日期问题 formatDate(numb, format) { const time = new Date((numb - 1) * 24 * 3600000 + 1); time.setYear(time.getFullYear() - 70); const year = time.getFullYear() + ""; const month = time.getMonth() + 1 + ""; const date = time.getDate() - 1 + ""; if (format && format.length === 1) { return year + format + month + format + date; } return ( year + (month < 10 ? "0" + month : month) + (date < 10 ? "0" + date : date) ); }, // 导入Excel importfxx() { let _this = this; let f = event.currentTarget.files[0]; let rABS = false; //是否将文件读取为二进制字符串 let reader = new FileReader(); //if (!FileReader.prototype.readAsBinaryString) { FileReader.prototype.readAsBinaryString = function (f) { let binary = ""; let rABS = false; //是否将文件读取为二进制字符串 let wb; //读取完成的数据 let outdata; let reader = new FileReader(); reader.onload = function (e) { let bytes = new Uint8Array(reader.result); let length = bytes.byteLength; for (let i = 0; i < length; i++) { binary += String.fromCharCode(bytes[i]); } let 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就是你想要的东西 const keyObj = { 序号: "id", 情况跟踪: "track", 日期: "date", 标题: "title", 状态: "status", 结果: "result", 预警: "warning", }; outdata.forEach((item) => { // 将中文的键名替换成英文的 for (let k in keyObj) { let newKey = keyObj[k]; if (newKey) { item[newKey] = item[k]; delete item[k]; } } item["date"] = _this.formatDate(item["date"], "-"); }); console.log(outdata); }; reader.readAsArrayBuffer(f); }; if (rABS) { reader.readAsArrayBuffer(f); } else { reader.readAsBinaryString(f); } }, }
如上操作之后,打印结果是如下
加载全部内容