前端总结03-使用JS-XLSX导入表格

389 阅读1分钟

背景:在做后台管理系统的时候,相信导入表格是很常见的,下面就来说说导入表格的具体操作吧,基于VUE的案例

模板

<el-upload
    class="upload-demo"
    ref="upload"
    action
    :multiple="false"
    :limit="1"
    v-model="Uploadform.file"
    list-type="text"
    :show-file-list="true"
    :on-change="handleChange"
    :auto-upload="false"
>
    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
</el-upoad>

数据

data () {
    Uploadform:{
        file""
    }
}

JS

handleChange(file) {
    console.warn(file)
    this.importSlsx(file)
},
importSlsx(file,opts){
    let _this = this
    return new Promise(function (resolve, reject) {
        const reader = new FileReader()
        reader.onload = function (e) {
            opts = opts || {};
            opts.type = 'binary';
            opts._dateType = opts._dateType || 1//1,"yyyy-MM-dd hh:mm",2,时间戳
            opts._numberType = opts._numberType || 1//1,不适用科学计数法,2,使用科学计数法
            const wb = _this.$XLSX.read(e.target.result, opts);
            // 定义一个keyMap把中文的key换成英文的
            letkeyMap = {'姓名':'name','序号':'idx','打卡记录':'record','日期':'time','部门':'branch'}
            letnewTabData = []
            Object.keys(wb.Sheets).map(key=>{
                letdata = _this.$XLSX.utils.sheet_to_json(wb.Sheets[key])
                //遍历每一项
                data.map( item=>{
                    //定义一个对象,存转换后的值
                    letd = {}
                    Object.keys( item ).map( keyItem =>{
                        d[keyMap[keyItem]] = item[keyItem]
                     })
                    //添加到最后的数据
                    newTabData.push(d)
                    console.warn(newTabData)
                })
            })
        }
    }
}

以上的代码就已经完成了表格导入和把中文的key转换成了英文

1617851858(1).jpg 这是一开始导入没有转换key是的数据,显然这不是我们要的数据格式

1617853017(1).jpg

通过转换之后就变成了我们想要的数据了

当然了,如果是把表格的这些内容全部上传到服务器,这时候前端可以不做处理,直接把获取的文件上传到服务器,后端来对这些数据的校验和修复