js读取excel表格

js处理excel表格需要引入相应的js文件,在这里你可以下载。详细请看代码。

analyzeFile(file){
    let reader = new FileReader();
    
    reader.onload = (e) => {
        /* Parse data */
        let bstr = e.target.result;
        let wb = XLSX.read(bstr, { type: 'binary', cellDates: true});
        /* Get first worksheet */
        let wsname = wb.SheetNames[0];
        let ws = wb.Sheets[wsname];
        /* Convert array of arrays */
        let data = XLSX.utils.sheet_to_json(ws, { header: 1});
        //this.importFileForm用来接收从excel读取到的对象数组
        this.importFileForm = constructData(data);
    }

    reader.readAsBinaryString(file);
    
    function constructData (data) {
        let res = [];
        if (!data || data.length < 2)
            return res;
        let num = 1;
        for (let i = 1; i < data.length; i++) {
            let user = {};
            let row = data[i];
            if (row.length !== 0) {
            	//向user对象填入相对应的列数据
                user.key = num;
                user.num = num;
                user.name = row[0];
                user.phoneNumber = row[1];
                user.certificatesType = row[2];
                user.certificatesNumber = row[3];
                user.marriageState = row[4];
                user.department = row[5];
                user.stage = row[6];
                user.email = row[7];
                user.role = row[8];
                user.entryTime = dateFromat(row[9]);
                if (checkParams(user)) {
                    res.push(user);
                    num++;
                }
            }
        }
        return res;
    }

	//如果excel表格中需要处理时间,你可以使用这个函数
    function dateFromat(value) {
        if (typeof value == "undefined" || value == "") {
            return value
        }
        let date = new Date(value);
        let year = date.getFullYear();
        let month = date.getMonth();
        let day = date.getDate()
        if (!isNaN(year) || !isNaN(month) || !isNaN(day)) {
            let dateSfd = year + "年" + (month + 1) + "月" + day + "日";
            return dateSfd;
        }
        return "undefined";
    }

	//检测字段内容是否正确
    function checkParams (val) {
        if (val.name == "" || val.name.trim() == "")
            return false;
        if (val.certificatesType != "身份证" && val.certificatesType != "护照" && val.certificatesType != "回乡证")
            return false;
        if (val.certificatesNumber == "" || !isValidCard(val.certificatesNumber))
            return false;
        if (val.phoneNumber == "" || isNaN(val.phoneNumber))
            return false;
        if (val.marriageState != "已婚" && val.marriageState != "未婚" && val.marriageState != "未知")
            return false;
        if(!val.entryTime || val.entryTime == "undefined") {
            return false;
        }
        return true;
    }
}, 
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页