Vue3 uses the xlsx library to upload excel files locally, and the front end parses them into Json data

Requirements: Upload the excel file locally, but need to perform some operations on the content of the excel file (addition, deletion, modification, etc.) and then upload it to the back-end server, then the front-end needs to parse the excel file.

Benefits: Do not use the background to read Excel data and echo table data, reduce front-end and back-end interactions, reduce the pressure on the back-end server, and use the front-end to operate.

Implementation: through the xlsx library

1. Download dependencies

npm install xlsx --save

2. Page usage

import * as XLSX from 'xlsx' // vue3可用此引入
import XLXS from "xlsx"; // vue2可用此引入

3. Page code writing

  <input
     type="file"
     accept=".xls,.xlsx"
     class="upload-file"
   @change="changeExcel($event)" />
const tableData = ref([])
function changeExcel(e){
    
    
  const files = e.target.files
   if (files.length <= 0) {
    
    
      return false
    } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
    
    
      console.log('上传格式不正确,请上传xls或者xlsx格式')
      return false
    }
    // 读取表格
    const fileReader = new FileReader()
      fileReader.onload = ev => {
    
    
        const workbook = XLSX.read(ev.target.result, {
    
    
          type: "binary"
        })
        const wsname = workbook.SheetNames[0]
        const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])
        console.log('ws:',ws) // 转换成json的数据
        //  dealExcel(ws) ...对数据进行自己需要的操作 
        tableData.value = ws
    }
    fileReader.readAsBinaryString(files[0])
}

4. The converted json data is not the data structure we need. At this time, it can be converted by the following method

  • Structure before conversion

insert image description here

  • converted structure

insert image description here

  • conversion method
function dealExcel(ws){
    
    
  let keymap = {
    
      // 我们要转换的开头
    "员工": "name",
    "工号": 'num',
    "登录账号": 'account',
    "部门": 'department'
  }
  ws.forEach(sourceObj => {
    
    
    Object.keys(sourceObj).map(keys => {
    
    
      let newKey = keymap[keys]
      if (newKey) {
    
    
        sourceObj[newKey] = sourceObj[keys]
        delete sourceObj[keys]
      }
    })
  })
  tableData.value = ws
}

Guess you like

Origin blog.csdn.net/Smile_666666/article/details/123297477