无法使用javascript

时间:2016-07-15 12:47:48

标签: javascript json excel

我正在尝试将xls文件转换为json我可以成功转换它但是当我尝试将xlsx文件转换为json时,我得到一个错误"未捕获的标题签名:预期d0cf11e0a1b11ae1看到了504b030414000808"。

的index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>XL to JSON</title>

    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script src=" https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.js"></script>
</head>
<body>
    <input type="file" id="my_file_input" />
    <div id='my_file_output'></div>

    <script>
        var oFileIn;

        $(function() {
            oFileIn = document.getElementById('my_file_input');
            if(oFileIn.addEventListener) {
                oFileIn.addEventListener('change', filePicked, false);
            }
        });


        function filePicked(oEvent) {
            // Get The File From The Input
            var oFile = oEvent.target.files[0];
            var sFilename = oFile.name;
            // Create A File Reader HTML5
            var reader = new FileReader();

            // Ready The Event For When A File Gets Selected
            reader.onload = function(e) {
                var data = e.target.result;
                var cfb = XLS.CFB.read(data, {type: 'binary'});
                var wb = XLS.parse_xlscfb(cfb);
                // Loop Over Each Sheet
                wb.SheetNames.forEach(function(sheetName) {
                    // Obtain The Current Row As CSV
                    var sCSV = XLS.utils.make_csv(wb.Sheets[sheetName]);
                    var oJS = XLS.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);

                    $("#my_file_output").html(sCSV);
                    console.log(oJS)
                });
            };

            // Tell JS To Start Reading The File.. You could delay this if desired
            reader.readAsBinaryString(oFile);
        }
    </script>
</body>
</html>

任何人都可以告诉我应该怎样解决这个问题。我很不理解这个问题。谢谢。

4 个答案:

答案 0 :(得分:0)

您正在使用不支持xlsx文件的xls库。请使用更新的:

https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js

您可以找到有关此here的更多详细信息和文档。

答案 1 :(得分:0)

它使用了这段代码:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>JS-XLSX Live Demo</title>
    <style>
        #b64data
        {
            width:100%;
        }
    </style>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<b>JS-XLSX (XLSX/XLSB/XLSM/XLS/XML) Live Demo</b><br />
<div id="drop"></div>
<p><input type="file" name="xlfile" id="xlf" /></p>
<br />
<pre id="out"></pre>
<br />
<script src="shim.js"></script>
<script src="jszip.js"></script>
<script src="xlsx.js"></script>
<!-- uncomment the next line here and in xlsxworker.js for ODS support -->
<script src="ods.js"></script>
<script>
    var X = XLSX;
    var XW = {
        /* worker message */
        msg: 'xlsx',
        /* worker scripts */
        rABS: './xlsxworker2.js',
        norABS: './xlsxworker1.js',
        noxfer: './xlsxworker.js'
    };
    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;
    }
    function get_radio_value( radioName )
    {
        var radios = document.getElementsByName( radioName );
        for( var i = 0; i < radios.length; i++ )
        {
            if( radios[i].checked || radios.length === 1 )
            {
                return radios[i].value;
            }
        }
    }
    function to_json(workbook)
    {
        var result = {};
        var result1 = [];
        var array1 = [];
        var arr =[];
        workbook.SheetNames.forEach(function(sheetName)
        {
            var arr = X.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
            var array_lenght = arr.length;
            for(var i = 0 ;i<array_lenght;i++ )
            {
                if(arr.length > 0)
                {
                    array1 = arr[i];
                    result = array1;
                    result1.push(array1);
                }
            }
        });
        var sub_key = [];
        for(var ab in result1)
        {
            var key = ab;
            var val = result1[ab];
            for(var j in val)
            {
                sub_key.push(j);
                console.log(sub_key);
            }
            if((sub_key.indexOf("Last Name")  && sub_key.indexOf("Email") && sub_key.indexOf("First Name")) > -1)
            {
                return "right format";
            }
            else
            {
                return "wrong format";
            }
        }
    }
    function process_wb(wb)
    {
        var output = "";
        switch(get_radio_value("format"))
        {
            case "json":
                output = JSON.stringify(to_json(wb), 2, 2);
                break;
            default:
                output = JSON.stringify(to_json(wb), 2, 2);
        }
        if(out.innerText === undefined) out.textContent = output;
        else out.innerText = output;
        if(typeof console !== 'undefined') console.log("output", new Date());
    }
    var xlf = document.getElementById('xlf');
    function handleFile(e)
    {
        rABS = document.getElementsByName("userabs")[0];
        use_worker = document.getElementsByName("useworker")[0];
        var files = e.target.files;
        var f = files[0];
        {
            var reader = new FileReader();
            var name = f.name;
            reader.onload = function(e)
            {
                if(typeof console !== 'undefined') console.log("onload", new Date());
                var data = e.target.result;
                if(use_worker)
                {
                    xw(data, process_wb);
                }
                else
                {
                    var wb;
                    if(rABS)
                    {
                        wb = X.read(data, {type: 'binary'});
                    } else
                    {
                        var arr = fixdata(data);
                        wb = X.read(btoa(arr), {type: 'base64'});
                    }
                    process_wb(wb);
                }
            };
            if(rABS) reader.readAsBinaryString(f);
            else reader.readAsArrayBuffer(f);
        }
    }
    if(xlf.addEventListener) xlf.addEventListener('change', handleFile, false);
</script>
</body>
</html>

答案 2 :(得分:0)

这个答案可能有用,但我并不认为它正是你所要求的。事实上,根据您的问题和SheetJS/js-xlsx的文档,我会建议这样的事情:

function filePicked(oEvent) {
// Get The File From The Input
var oFile = oEvent.target.files[0];
var sFilename = oFile.name;
// Create A File Reader HTML5
var reader = new FileReader();

// Ready The Event For When A File Gets Selected
reader.onload = function(e) {
    var data = e.target.result;
    var cfb = XLSX.read(data, {type: 'binary'});
    console.log(cfb)
    cfb.SheetNames.forEach(function(sheetName) {
        // Obtain The Current Row As CSV
        var sCSV = XLS.utils.make_csv(cfb.Sheets[sheetName]);   
        var oJS = XLS.utils.sheet_to_json(cfb.Sheets[sheetName]);   

        $("#my_file_output").html(sCSV);
        console.log(oJS)
        $scope.oJS = oJS
    });
};

// Tell JS To Start Reading The File.. You could delay this if desired
reader.readAsBinaryString(oFile);}

我尝试过它并且运行正常。最重要的是,它是你问题的真正答案。

答案 3 :(得分:0)

<script type="text/javascript">

document.querySelector("html").classList.add('js');

var fileInput  = document.querySelector( ".input-file" ),  
    button     = document.querySelector( ".input-file-trigger"),
    the_return = document.querySelector(".file-return");

button.addEventListener( "keydown", function( event ) {  
    if ( event.keyCode == 13 || event.keyCode == 32 ) {  
        fileInput.focus();
    }
});
button.addEventListener( "click", function( event ) {
   fileInput.focus();
   return false;
}); 
fileInput.addEventListener( "change", function( event ) {  

    var oFile = event.target.files[0];
    var sFilename = oFile.name;
    var reader = new FileReader();

    // Ready The Event For When A File Gets Selected
    reader.onload = function(e) {
        var data = e.target.result;
        var cfb = XLSX.read(data, {type: 'binary'});
        // Loop Over Each Sheet
        cfb.SheetNames.forEach(function(sheetName) {
                        var sCSV = XLS.utils.make_csv(cfb.Sheets[sheetName]);   
                        var oJS = XLS.utils.sheet_to_json(cfb.Sheets[sheetName]);   
            alert(oJS);
            alert(sCSV);
        });
    };
    // Tell JS To Start Reading The File.. You could delay this if desired
    reader.readAsBinaryString(oFile);


});