js-xlsx前端导入excel解析数据

xlxs 版本2.2
files.js
 

import FileSaver from 'file-saver';
import XLSX from 'xlsx';

/**
 * 导出 Excel
 * @param {*} el dom选择器
 * @param {*} name 保存文件名称
 */
export const table_to_book = ({el = '.el-table', name = 'sheetjs'} = {}) => {
    let dom = document.querySelector(el);
    if (!el) {
        throw new Error(el + ',未找到');
    }
    /* generate workbook object from table */
    let wb = XLSX.utils.table_to_book(dom);
    /* get binary string as output */
    let wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
    });
    FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), `${name}.xlsx`);
    return wbout;
};

// 导入
export const sheet_to_json = (file,callback) => {
    /* Boilerplate to set up FileReader */
    const reader = new FileReader();
    reader.onload = (e) => {
        /* Parse data */
        const bstr = e.target.result;
        const wb = XLSX.read(bstr, {type:'binary'});
        /* Get first worksheet */
        const wsname = wb.SheetNames[0];
        const ws = wb.Sheets[wsname];
        /* Convert array of arrays */
        const data = XLSX.utils.sheet_to_json(ws, {header:1});
        let arr = []
        data.forEach(i=>{
            if (i.length) {
                arr.push(i) 
            }
        })
        if(callback && typeof callback == 'function') callback(arr);
        console.log("arr----",arr);
        /* Update state */
        // this.data = data;
        // this.cols = make_cols(ws['!ref']);
    };
    reader.readAsBinaryString(file);
};

//  导入  没数据也出来下标。好做判断
export const sheet_to_json_all = (file,callback) => {
    /* Boilerplate to set up FileReader */
    const reader = new FileReader();
    reader.onload = (e) => {
        /* Parse data */
        const bstr = e.target.result;
        const wb = XLSX.read(bstr, {type:'binary'});
        /* Get first worksheet */
        const wsname = wb.SheetNames[0];
        const ws = wb.Sheets[wsname];
        /* Convert array of arrays */
        const data = XLSX.utils.sheet_to_json(ws, {header:1,defval:"",blankrows:false,raw:false});      
        let arr = []
        data.forEach(i=>{     
            if (i.length) {     
               arr.push(i)     
            }       
        })
        if(callback && typeof callback == 'function') callback(data);
        console.log("arr----",arr);       
    };
    reader.readAsBinaryString(file);
};

调用sheet_to_json_all()

空列数据变空字符串:defval:""
数字类型格式化为文本格式:raw:false
空的行不读取(如果不设置则空的行数据也会每个列有一个空字符串): blankrows:false

Guess you like

Origin blog.csdn.net/weixin_43075758/article/details/117126652