前端使用xlsx插件讀取excel文件數(shù)據(jù)

安裝xlsx插件

npm install xlsx

導(dǎo)入xlsx

import XLSX from 'xlsx'

前端UI如下:

文件上傳.png
<bk-upload
        :tip="'只允許上傳JPG、PNG、JPEG的文件'"
        :with-credentials="true"
        :accept="'.xlsx, .xls'"
        @custom-request="getExcel"
        :multiple="false">
</bk-upload>

點(diǎn)擊上傳:

getExcel (file) {
    console.log(file)
     const types =file.fileObj.name.split(".")[1] 
    const fileType = ["xlsx","xls"].some( 
        item => item === types 
    ) 
    if(!fileType){ 
        return false
    }
    this.analysis(file).then(tableJson =>{ 
        if (tableJson && tableJson.length > ){
            this.formData.storages =[]
            const dataExcel=tableJson[0] 
            const data=JSON.parse(JSON.stringify(dataExcel.sheet)) 
            const items = data.map(ite => { 
                return { 
                    'dish_num':ite['盤號'],
                    'store_name':ite['數(shù)據(jù)存儲名'],
                    'key': ite['盤號'] +'_'+ ite['數(shù)據(jù)存儲名'] 
                }
            }) 
            this.formData.storages = items 
        }
    })
}

得到的文件信息如下,在這里只需要關(guān)注fileList中的origin內(nèi)容


391693555688_.pic_hd.jpg

對得到的文件信息進(jìn)行處理,使用FileReader

主要分為三步:

1、構(gòu)建FileReader對象
2、使用reader.readAsBinaryString()指定需要讀取的內(nèi)容,一旦完成,result屬性中將包含所讀取文件的原始二進(jìn)制數(shù)據(jù)
3、在reader.onload中觸發(fā)讀取完成之后的操作

analysis (file){
    return new Promise(function (resolve) {
        # 1、構(gòu)建FileReader對象
        const reader =new FileReader()
        # 3、讀取完成時(shí)的操作
        reader.onload = function (e){
            # 使用XLSX解析讀取到的數(shù)據(jù)
            const data = e.target.result
            const datajson = XLSX.read(data, {type: "binary"})
            const result = []
            datajson.SheetNames.forEach(sheetName => {
                result.push({
                    sheetName: sheetName,
                    sheet: xLsx.utils.sheet_to_json(datajson.Sheets[sheetName])
                })
            })
            resolve(result)
        }
        # 2、傳入需要讀取的內(nèi)容
        reader.readAsBinaryString(file.fileList[0].origin)
    })
}

XSLX解析二進(jìn)制數(shù)據(jù),使用XLSX.read(data, {type: type})來完成

type的類型如下

base64: 以base64方式讀取
binary: BinaryString格式(byte n is data.charCodeAt(n))

string: UTF8編碼的字符串
buffer: nodejs Buffer
array: Uint8Array,8位無符號數(shù)組
file: 文件的路徑(僅nodejs下支持)

我們這里使用的是binary,讀取到的數(shù)據(jù)如下:

401693557607_.pic.jpg

解析sheet的方法如下:

XLSX.utils.sheet_to_csv:生成CSV格式
XLSX.utils.sheet_to_txt:生成純文本格式
XLSX.utils.sheet_to_html:生成HTML格式
XLSX.utils.sheet_to_json:輸出JSON格式

我們在這里使用XLSX.utils.sheet_to_json,XLSX.utils.sheet_to_json(data, type)有兩個(gè)參數(shù),第一個(gè)是我們wordBook對象里面Sheets對象對應(yīng)的數(shù)據(jù),第二個(gè)參數(shù)配置如下:

raw: 使用原始值 (true) 或格式化字符串 (false)  (默認(rèn)值:true)
dateNF: 在字符串輸出中使用指定的日期格式(默認(rèn)值:FMT 14)
defval: 使用指定值代替 null 或 undefined ()
blankrows: 在輸出中包含空行**(默認(rèn)值:** )
range: 

        (number)使用工作表范圍,但將起始行設(shè)置為值

        (String)使用指定范圍(A1 樣式的有界范圍字符串

        (default)使用工作表范圍 ( worksheet[‘!ref’])

header:

        1: 生成數(shù)組數(shù)組(“二維數(shù)組”)

        "A".行對象鍵是文字列標(biāo)簽

        array of strings: 使用指定的字符串作為行對象中的鍵

        (default): 將第一行作為鍵讀取并消除歧義

默認(rèn)是將第一行作為鍵讀取數(shù)據(jù),xLsx.utils.sheet_to_json(datajson.Sheets[sheetName])讀取到的數(shù)據(jù)如下:

431693558934_.pic_hd.jpg

擴(kuò)展:讀取復(fù)雜表頭的表格

復(fù)雜表頭使用,XLsx.utils.sheet_to_json(datajson.Sheets[sheetName], {header: 1},生成二維數(shù)組

mulAnalysis (file){
    return new Promise(function (resolve) {
        const reader = new FileReader()
        reader.onload = function(e){
            const data =e.target.result
            const datajson = XLSx.read(data,{type: "binary"})
            const result = []
            datajson.SheetNames.forEach(sheetName => {
                const items = XLsx.utils.sheet_to_json(datajson.Sheets[sheetName], {header: 1}
                result.push({
                    sheetName: sheetName,
                    sheet: items.splice(2, items.length)
                })
            })
            resolve(result)
        }
        reader.readAsBinaryString(file.fileList[0].origin)
    })
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容