La vue côté PC pour l'examen frontal du projet télécharge Excel et l'analyse avec xlsx

Écrivez le titre du répertoire ici

1. Demande

Le frontal télécharge le fichier Excel et analyse les champs de la page en fonction du contenu du modèle du fichier Excel. Ce processus ne nécessite pas la participation du back-end.
Principalement utilisé XLSX.utils.sheet_to_json

2. Mise en œuvre

2.1 HTML

                <el-upload
                  style="margin-left: 20px"
                  :auto-upload="false"
                  class="upload-demo"
                  drag
                  accept=".xls,.xlsx"
                  :on-change="handleChangeFile"
                  :limit="1"
                  action="#">
<!--                  <i class="el-icon-upload"></i>-->
                  <div class="el-upload__text">点击或将文件拖拽到这里上传</div>
                </el-upload>

Logique 2.2 js

Méthode 1 (recommandée) :

import XLSX from 'xlsx';
handleChangeFile(file) {
    
    
  const reader = new FileReader();
  reader.onload = () => {
    
    
    const txt = reader.result;
    const wb = XLSX.read(txt, {
    
    
      type: 'binary',
    });
    const json = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
    // 到json就可以获取到解析后的结果了
	this.xxx = xxx; // 把结果更新到页面上
  }
  reader.readAsBinaryString(file.raw);
},

Méthode 2 :

    // 导入表格
    handleChangeFile1(param) {
    
    
      const that = this;
      that.file2Xce(param).then((item) => {
    
    
        if (item && item.length > 0) {
    
    
          // xlsxJson就是解析出来的json数据,数据格式如下
          // [{sheetName: sheet1, sheet: sheetData }]
          if (item[0] && item[0].sheet && item[0].sheet.length) {
    
    
            // that.tableData = item[0].sheet; // 把数据塞到表格预览
            console.log('有的----', item[0].sheet);
          }
        }
      }).catch((error) => {
    
    
        // loading.close();
        console.log('importExcel error', error);
      });
    },
    /**
     * 解析文件
     * @param {Object} file
     */
    file2Xce(file) {
    
    
      return new Promise((resolve) => {
    
    
        const reader = new FileReader();
        reader.readAsBinaryString(file.raw);
        reader.onload = (e) => {
    
    
          const data = e.target.result;
          this.wb = XLSX.read(data, {
    
    
            type: 'binary',
          });
          const result = [];
          this.wb.SheetNames.forEach((sheetName) => {
    
    
            result.push({
    
    
              sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName]),
            });
          });
          resolve(result);
        };
      });
    },

おすすめ

転載: blog.csdn.net/s18438610353/article/details/124302432