乐趣区

关于前端:Vue中导入Excel文件

以将此 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);
      }
    },
}

如上操作之后,打印后果是如下:

退出移动版