Shweta Shweta - 4 months ago 233
Javascript Question

Can not convert xlsx file into json using javascript

I am trying to convert xls file into json I can convert it successfully but when I try to convert xlsx file into json I get an error as "Uncaught Header Signature: Expected d0cf11e0a1b11ae1 saw 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>


Can any one please tell me how should I solve this.I am badly stucked in this problem.Thanks in advance.

Answer

It worked with this code:

<!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>