Home  >  Article  >  Web Front-end  >  js parses local Excel files

js parses local Excel files

不言
不言Original
2018-04-03 14:49:052101browse


Parsing Excel files is usually done on the backend, but today I encountered the need to parse and process Excel file data on the frontend. I specially recorded an implementation method:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>解析Excel文件</title></head><body>
    <input type="file" onchange="importf(this)" /></body><script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script><script src="https://cdn.bootcss.com/xlsx/0.12.6/xlsx.full.min.js"></script><script type="text/javascript">
    var wb;// 读取完成的数据
    var rABS = false; // 是否将文件读取为二进制字符串

    // 导入
    function importf(obj) {
        if (!obj.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 : &#39;base64&#39;
                });
            } else {
                wb = XLSX.read(data, {
                    type : &#39;binary&#39;
                });
            }            // wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
        // wb.Sheets[Sheet名]获取第一个Sheet的数据JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]));
        };        if (rABS) {
            reader.readAsArrayBuffer(f);
        } else {
            reader.readAsBinaryString(f);
        }
    }    // 文件流转BinaryString
    function fixdata(data) {
        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></html>



The above is the detailed content of js parses local Excel files. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn