Vue uses js to read Excel data

JS reads Excel data

Why do you want to import Excel data? Almost all systems involve the function of adding data. There are two ways to add data. The first is to manually input data. You can only input one piece of data at a time. The other is to add multiple pieces of data by importing an excel file.
Next, we will use an example to import excel data

1. Sample code

<template>
  <div class="hello">
    <h1>{
    
    {
    
     msg }}</h1>
    <h2>Essential Links</h2>
    <el-row>
      <el-col>
        <el-upload
          ref="upload"
          action="/"
          :show-file-list="false"
          :on-change="(file, fileList) => {batchImport(file, fileList,importHeader)}"
          :auto-upload="false"
          style="margin-left: 30px;width:130px">
          <el-button
            style="width: 130px"
            type="primary"
            plain
            icon="el-icon-upload2"
            class="handle-del">批量导入
          </el-button>
        </el-upload>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import XLSX from "xlsx";
export default {
    
    
  name: 'HelloWorld',
  data () {
    
    
    return {
    
    
      xlsxJson: {
    
    },
      importHeader:["姓名","年龄"],
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods:{
    
    
    batchImport(file, fileList,header) {
    
    
      // let file = file.files[0] // 使用传统的input方法需要加上这一步
      const types = file.name.split(".")[1];
      const fileType = ["xlsx", "xlc", "xlm", "xls", "xlt", "xlw", "csv"].some(
        (item) => item === types
      );
      if (!fileType) {
    
    
        alert("格式错误!请重新选择");
        return;
      }
      this.file2Xce(file,header).then((tabJson) => {
    
    
        if (tabJson && tabJson.length > 0) {
    
    
          this.xlsxJson = tabJson;
        }
        this.setLedgerList();
      });
    },
    setLedgerList() {
    
    
      let data = [];

      this.xlsxJson[0].sheet.forEach((item) => {
    
    
        data.push(item);
      });
      console.log(data)
    //  这个data就可以传给后端,存入数据了
    },
    file2Xce(file,header) {
    
    
      return new Promise(function (resolve, reject) {
    
    
        const reader = new FileReader();
        reader.onload = function (e) {
    
    
          const data = e.target.result;
          // XLSX.read返回值为WorkBook对象,包含整个文件的所有表
          this.wb = XLSX.read(data, {
    
    
            type: "binary",
          });
          const result = [];
          //SheetNames包含了文件中所有的表明
          this.wb.SheetNames.forEach((sheetName) => {
    
    
            result.push({
    
    
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName], {
    
    
                //header是设置表属性名,如果设置为数字,则属性名由0,1,2...表示
                //此处设置的header为importHeader:["姓名","年龄"],最终结果的属性名对应该数组
                header: header,
              }),
            });
          });
          console.log("result")
          console.log(result)
          //将excel文件第一张表的第一项(excel的第一行为属性名,应该去掉)删除
          result[0].sheet.shift();
          resolve(result);
        };
        reader.readAsBinaryString(file.raw);
        // reader.readAsBinaryString(file) // 传统input方法
      });
    },
  }
}
</script>

2. Analysis of results

2.1 Material

The excel file contains two tables
Table 1
insert image description here
Table 2
insert image description here

2.2 Code Analysis and Results

The file2Xce function obtains the data
results
of two tables and parses the two tables in the excel file.
insert image description here
Each table has two attributes:
sheet: the data of the
table sheetName: the name of the table The data in the
insert image description here
first table, if the file2Xce function does not add the header parameter , the property name (marked by the red arrow) will not be displayed. The
insert image description here
setLedgerList function stores the data in the table in data, which is passed to the backend as the data of the subsequent request link.
insert image description here

3. Summary

The file2Xce function here just removes the attribute value of the first row of the first table, and the second table is not processed, so setLedgerList just passes the value of the first table to data.
There are some flaws in this example: the fields of the two tables used in this example are different. Under normal circumstances, the fields of the two tables should be the same, so that the operation of multiple tables can be realized through forEach, that is, the data of the two tables are stored in data.

Guess you like

Origin blog.csdn.net/weixin_43424325/article/details/121016717