美文网首页
读取excel数据

读取excel数据

作者: 人生如戏戏如人生_5f71 | 来源:发表于2020-09-07 13:28 被阅读0次

1:先安装第三方插件

npm install xlsx

2:在文件中引入

import XLSX from 'xlsx'

将读取表格文件的js封装成一个函数,并用Promise返回读取表格结果

function uploadExcel (file) {

    return new Promise(function (resolve,reject) {

        let reader = new FileReader()

        reader.readAsBinaryString(file)

        reader.onload = function(e) {

                //workbook存放excel的所有基本信息

                let workbook = XLSX.read(e.target.result, {type: 'binary'})

                //定义sheetList中存放excel表格的sheet表,就是最下方的tab

                let sheetList = workbook.SheetNames

                //存放字符串数组格式的表格数据

                let formulaeResult = []

                //存放json数组格式的表格数据

                let jsonResult = []

                //读取第一个sheet

                jsonResult = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])

                formulaeResult = XLSX.utils.sheet_to_formulae(workbook.Sheets[workbook.SheetNames[0]])

                let header = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]],{header:1})

 //读取所有的sheet

                // sheetList.forEach(function(y) {

                    // let json = XLSX.utils.sheet_to_json(workbook.Sheets[y])

                    // let formulae = XLSX.utils.sheet_to_formulae(workbook.Sheets[y])

                    // if(json.length >0){

                        // jsonResult.push(...json)

                        // formulaeResult.push(...formulae)

                //  }

                 // });

                let result = {header:header[0],

                             list:jsonResult}

                resolve(result)

        }

    })

}

相关文章

网友评论

      本文标题:读取excel数据

      本文链接:https://www.haomeiwen.com/subject/hbikektx.html