Excel to JSON javascript code?

后端 未结 4 1073
予麋鹿
予麋鹿 2020-12-04 13:03

I want to convert excel sheet data to json. It has to be dynamic, so there is an upload button where user uploads the excel sheet and the data is then converted into json. C

4条回答
  •  时光说笑
    2020-12-04 13:27

    The answers are working fine with xls format but, in my case, it didn't work for xlsx format. Thus I added some code here. it works both xls and xlsx format.

    I took the sample from the official sample link.

    Hope it may help !

    function fileReader(oEvent) {
            var oFile = oEvent.target.files[0];
            var sFilename = oFile.name;
    
            var reader = new FileReader();
            var result = {};
    
            reader.onload = function (e) {
                var data = e.target.result;
                data = new Uint8Array(data);
                var workbook = XLSX.read(data, {type: 'array'});
                console.log(workbook);
                var result = {};
                workbook.SheetNames.forEach(function (sheetName) {
                    var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header: 1});
                    if (roa.length) result[sheetName] = roa;
                });
                // see the result, caution: it works after reader event is done.
                console.log(result);
            };
            reader.readAsArrayBuffer(oFile);
    }
    
    // Add your id of "File Input" 
    $('#fileUpload').change(function(ev) {
            // Do something 
            fileReader(ev);
    }
    

提交回复
热议问题