首页 > 其他分享 >vue3中读取本地excel文件内容

vue3中读取本地excel文件内容

时间:2023-03-03 20:55:44浏览次数:57  
标签:xlsx const 读取 XLSX excel vue3 obj any

背景

  做后台项目时避免不了excel文件上传,有的还要求对文件内容做校验,或者把文件内容转成数据上传保存.

操作

  1.引入xlsx插件,最好安装指定版本,否则会报错

npm i xlsx@0.16.0 -save

  2.页面引入 

import XLSX from 'xlsx'

  3.页面触发

<el-upload class="upload-demo" ref="upload" accept=".xls,.xlsx" action="" :on-change="uploadExcel"
                    :show-file-list="false" :auto-upload="false">
                    <el-button slot="trigger" size="large">导入excel</el-button>
                </el-upload>

  4.使用处理数据

import { ref } from 'vue'
import XLSX from 'xlsx'
const menuData: any = ref([])
const tableData: any = ref([])
const uploadExcel = (file: any, fileList: any) => {
    let files = { 0: file.raw }
    const fileReader = new FileReader()
    fileReader.onload = (e: any) => {
        try {
            const workbook = XLSX.read(e.target.result, {
                type: 'binary'
            })
            const wsname = workbook.SheetNames[0] // 取第一张表
            const ws: any = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])// 生成json表格内容
            const data: any = []
            ws.map((item: any) => {
                let obj: any = {
                    arr:[]
                }
                Object.values(item).map((child: any, index: number) => {
                    obj.arr.push('name' + index)
                    obj[`name${index}`] = child
                })
                data.push(obj)
            })
            tableData.value = data
            menuData.value = Object.keys(ws[0])
        } catch (err) {
            console.log(err)
        }
    }
   fileReader.readAsBinaryString(files[0])
}

excel文件如下:

读取后,处理数据展示如下:

具体代码地址:https://gitee.com/yuexiayunsheng/vue3learn/blob/master/src/views/GetExcelContent.vue

    

 

标签:xlsx,const,读取,XLSX,excel,vue3,obj,any
From: https://www.cnblogs.com/foxing/p/17176742.html

相关文章