Vue3 implements uploading excel and parsing it into json data, generating json files for automatic download

Requirements:
Upload the excel file and parse it into data in json format through js.
Operate the acquired excel data and splice it into the desired generated file for download.

1. Install the xlsx plugin

cnpm install  xlsx

Plug-in xlsx to parse excel files
2. Create a new xlsx.js file, add the following code, and put it in the plugins or utils plugin folder

/* 读取文件 */
export const readFile = (file) => {
    
    
  return new Promise(resolve => {
    
    
    let reader = new FileReader()
    reader.readAsBinaryString(file)
    reader.onload = ev => {
    
    
      resolve(ev.target.result)
    }
  })
}

3. Developed in the vue3 project, the page code
introduces the js code of the downloaded file in index.html

  <script src="https://cdn.bootcdn.net/ajax/libs/FileSaver.js/2.0.5/FileSaver.js"></scrip

The following is the complete code of the page, the function is implemented based on vue3

<template>
  <div style="text-align:left;padding-left:30px;position:relative;z-index:1">
    <el-upload name="file"
               :multiple="false"
               :show-file-list="false"
               :auto-upload="false"
               :on-change="handleChange"
               style="margin-bottom:30px">
      <el-button type="primary">上传excel文件</el-button>
    </el-upload>  
  </div>
</template>

<script >
import {
      
       defineComponent, reactive, toRefs, getCurrentInstance } from 'vue'
import * as XLSX from 'xlsx'
import {
      
       readFile } from './xlsx'
export default defineComponent({
      
      
  setup(props, context) {
      
      
    const {
      
       proxy } = getCurrentInstance()
    const data = reactive({
      
      
      excelData: null
    })
    const handleChange = async (file, fileList) => {
      
      
      let dataBinary = await readFile(file.raw)
      let workBook = XLSX.read(dataBinary, {
      
       type: 'binary', cellDates: true })
      let workSheet = workBook.Sheets[workBook.SheetNames[0]]
      let data = XLSX.utils.sheet_to_json(workSheet)
	  console.log('读取到的excel的内容',data)
	  
      data.forEach((row) => {
      
      
       console.log('对数据进行操作')
      })
      
        var jsonFile = JSON.stringify(data)
        var blob = new Blob([jsonFile], {
      
      
          type: 'text/plain;charset=utf-8'
        })
        saveAs(blob, 'excel生成的.json')
      }
    }
    return {
      
      
      ...toRefs(data),
      handleChange
    }
  }
})
</script>

Guess you like

Origin blog.csdn.net/m0_49016709/article/details/129730282