js-xlsx 前段读取excel

JavaScript读取和导出excel示例(基于js-xlsx)

放入参考链接 http://demo.haoji.me/2017/02/08-js-xlsx/
github官网 https://github.com/SheetJS/sheetjs
需要引入js

直接上代码

<a class="btn btn-info" onclick="selectFile()">
         <input type="file" id="file" style="display:none;" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
         <i class="fa fa-plus"></i> <@ctx.i18n text = "导入Excel"/>
</a>

此代码段是有关 读取xls的所有函数

  function selectFile() {
        document.getElementById('file').click();
    }

    // 读取本地excel文件
    function readWorkbookFromLocalFile(file, callback) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var data = e.target.result;
            var workbook = XLSX.read(data, {type: 'binary'});
            if(callback) callback(workbook);
        };
        reader.readAsBinaryString(file);
    }



    function readWorkbook(workbook) {
        var sheetNames = workbook.SheetNames; // 工作表名称集合
        var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet
        var csv = XLSX.utils.sheet_to_csv(worksheet);
        csv2table(csv);
    }

    // 将csv转换成表格
    function csv2table(csv)
    {
        var rows = csv.split('\n');
        rows.shift();
        rows.pop();
        rows.forEach(function(row, idx) {
            var count = $("#bootstrap-table").bootstrapTable('getData').length;

            var columns = row.split(',');
            var rowinfo = {
                index:count+1
                ,invCode: columns[0]
                ,invName: columns[1]
                ,number: columns[3]
                ,unites: columns[5]
                ,singlePrice: 0
                ,size: columns[2]
                ,material: columns[4]
                ,remark: ""
            };
            $("#bootstrap-table").bootstrapTable('append', rowinfo)

        });
    }


    $(function() {
        document.getElementById('file').addEventListener('change', function(e) {
            var files = e.target.files;
            if(files.length == 0) return;
            var f = files[0];
            if(!/\.xlsx$/g.test(f.name)) {
                alert('仅支持读取xlsx格式!');
                return;
            }
            readWorkbookFromLocalFile(f, function(workbook) {
                readWorkbook(workbook);
            });
        });
    });

posted on 2021-06-08 10:57  三千世界a  阅读(284)  评论(0编辑  收藏  举报

导航