The front end parses the data in Excel for operation

Technical points: Vue, Element, JSON

Function description: Read the data in Excel, use JavaScript technology to convert the data into Json format for operation!

Function description: Only the front-end can be used to manipulate data, and the data is not transmitted to the back-end for processing!

caution caution caution

If there is only one row of data in your table that cannot be read, this method can only read tables with at least two rows!

(1) Such as this cannot be read.

insert image description here
(2) In this way, two lines can be read.

insert image description here

(3) Only limited to front-end operations, and does not provide excel data to the back-end

(1) Install the plug-in:

1. element dependency

(1) Install element dependencies

npm i element-ui -S

2. xlsx dependency

(1) Install xlsx dependencies

npm install xlsx

(2) Introduced in the file

import XLSX from "xlsx";

(2) Page development

1. Add Element component

      <el-upload
              action="/"
              :on-change="onChange"
              :auto-upload="false"
              :show-file-list="false"
              accept=".xls, .xlsx"
      >
        <el-button size="small" type="primary" class="upload-bom uploadBtn">
          <span class="iconXlSX-sty-test">导入最佳位置点</span>
        </el-button>
      </el-upload>

2. Add the methods method

(1) Introduce dependencies

import XLSX from "xlsx";

insert image description here

(2) File selection callback

// 文件选择回调
      onChange(file, fileList) {
    
    
          console.log(fileList)
          this.$confirm("此操作将永久覆盖名单, 是否继续?", "提示", {
    
    
              confirmButtonText: "确定",
              cancelButtonText: "取消",
          })
              .then(() => {
    
    
                  this.fileData = file; // 保存当前选择文件
                  console.log(file)
                  console.log(this.fileData )
                  this.readExcel(); // 调用读取数据的方法
              })
              .catch(() => {
    
    
                  this.$message({
    
    
                      type: "info",
                      message: "已取消",
                  });
              });
      },

(3) Excel table data processing

      // 读取数据
      readExcel(e) {
    
    
          console.log(e)
          let that = this;
          const files = that.fileData;
          console.log(files)
          if (!files) {
    
    
              // 如果没有文件 - 当然也可以提醒用户弹个警告框 但是基本没有这种情况的出现
              return false;
          } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
    
    
              // 文件格式的判断
              this.$message.error("上传格式不正确,请上传xls或者xlsx格式");
              return false;
          }
          const fileReader = new FileReader();
          fileReader.onload = (ev) => {
    
    
              try {
    
    
                  const data = ev.target.result;
                  const workbook = XLSX.read(data, {
    
    
                      type: "binary",
                  });
                  // 取第一张表
                  const wsname = workbook.SheetNames[0];
                  // 生成json表格内容
                  const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);
                  // 循环 ws 取得其中的数据
                  // 把 ws 打印出来 就可以看得很清楚了 之后就进行自己想要的操作就可以了
                  // 没有一样的代码 没有一样的需求
                  var temporary = [];
                  var temporaryValue = [];
                  // for (let i = 0; i < ws.length; i++) {
    
    
                  //     temporary.push([
                  //         ws[i].姓名 + "",
                  //         ws[i].年龄,
                  //     ]);
                  // }
                  //第一种方式
                  console.log("JSON数据转换")
                  console.log(ws[0])
                  console.log(ws[1])
                  console.log("JSON数据转换")
                  
                  //对Json数据进行处理
                  for( var attr in ws[1] ){
    
    
                      console.log( attr + ' : ' + ws[1][attr] );  
                      // 注意这里访问不能用.访问,也不能加引号,否则就代表访问的是json里面名称为attr的值了
                      temporary.push(parseInt(attr))
                      temporaryValue.push(ws[1][attr])
                  }
                  this.init(temporaryValue);
                  this.DistributorList = temporary;
              } catch (e) {
    
    
                  return false;
              }
          };
          // 如果为原生 input 则应是 files[0]
          fileReader.readAsBinaryString(files.raw);
      },

(4) Notes

Note that if there is only one row of data in your table, it cannot be read. This method can only read tables with at least two rows!

3. JSON string processing method

(1) JSON string:

var jsonStr ='{
    
    "name":"Liza", "password":"123"}' ;

(2) JSON object:

var jsonObj = {
    
    "name":"Liza", "password":"123"};  //json对象的key键值对中的键必须带有“”

(3) JSON traversal:

var json1 = {
    
     'name' : 'yy' , 'age' : 11 , 'fun' : '前端开发' };
for( var attr in json1 ){
    
    
        alert( attr + ' : ' + json1[attr] );  // 注意这里访问不能用.访问,也不能加引号,否则就代表访问的是json里面名称为attr的值了
}

insert image description here

Guess you like

Origin blog.csdn.net/weixin_43388691/article/details/130063184