Vue3는 엑셀을 업로드하고 json 데이터로 파싱하여 자동 다운로드를 위한 json 파일을 생성합니다.

요구 사항:
엑셀 파일을 업로드하고 js를 통해 json 형식의 데이터로 구문 분석합니다.
취득한 엑셀 데이터를 조작하여 원하는 생성 파일에 접속하여 다운로드합니다.

1. xlsx 플러그인 설치

cnpm install  xlsx

Excel 파일을 구문 분석하기 위한 플러그인 xlsx
2. 새 xlsx.js 파일을 만들고 다음 코드를 추가한 후 plugins 또는 utils 플러그인 폴더에 넣습니다.

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

3. vue3 프로젝트에서 개발된 페이지 코드는
index.html에서 다운로드한 파일의 js 코드를 소개합니다.

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

다음은 페이지의 전체 코드이며 기능은 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>

추천

출처blog.csdn.net/m0_49016709/article/details/129730282