js解析本地Excel

下载插件地址:
 https://github.com/SheetJS/js-xlsx

 需要用到的js文件:xlsx.full.min.js、shim.js


<script src="./js/xlsx.full.min.js"></script>

    <body>
        <input type="file"onchange="importf(this)" />
        <div id="demo"></div>
        <script>
            /*
            FileReader共有4种读取方法:
            1.readAsArrayBuffer(file):将文件读取为ArrayBuffer。
            2.readAsBinaryString(file):将文件读取为二进制字符串
            3.readAsDataURL(file):将文件读取为Data URL
            4.readAsText(file, [encoding]):将文件读取为文本,encoding缺省值为'UTF-8'
                         */
            var wb;//读取完成的数据
            var rABS = false; //是否将文件读取为二进制字符串,ie浏览器不支持可将rABS置为true可以支持到ie10及以上

            function importf(obj) {//导入
                if(!obj.files) {     //ie9及以下版本没有files属性对象
                    return;
                }
                var f = obj.files[0];
                var reader = new FileReader();
                reader.onload = function(e) {
                    var data = e.target.result;
                    if(rABS) {
                        wb = XLSX.read(btoa(fixdata(data)), {//手动转化
                            type: 'base64'
                        });
                    } else {
                        wb = XLSX.read(data, {
                            type: 'binary'
                        });
                    }
                    //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
                    //wb.Sheets[Sheet名]获取第一个Sheet的数据
                    document.getElementById("demo").innerHTML= JSON.stringify( XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]) );
                };
                if(rABS) {
                    reader.readAsArrayBuffer(f);
                } else {
                    reader.readAsBinaryString(f);
                }
            }

            function fixdata(data) { //文件流转BinaryString
                var o = "",
                    l = 0,
                    w = 10240;
                for(; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
                o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
                return o;
            }
        </script>
    </body>
阅读更多

没有更多推荐了,返回首页