exceljs-xlsx

unable to read empty cells reading excel file using js-xlsx


I have an excel file I am reading using js-xlsx. The code is working fine except where the cells are empty. These cells are ignored. How do I get these cells also when creating my JSON object?

I went through some of the question on SO as well as some other forums for the same problem but nothing satisfactory.

Any help would be welcome. My code is:

 reader.addEventListener('load', function(){
        var data = this.result;
        var wb = XLSX.read(data, {type: 'binary', sheetStubs:true});
        //  console.log(headers);

        wb.SheetNames.forEach(function(sheetName){
            //pulling out column headers for tablecreation
            var headers = get_header_row(wb.Sheets[sheetName]);
            createTableInDB(headers);
            // Here is your object
            var XL_row_object = XLSX.utils.sheet_to_json(wb.Sheets[sheetName]);
            //console.log(XL_row_object);

            for(var i=0; i<XL_row_object.length; i++){
                var json_object = XL_row_object[i];

                if(json_object !== null){
                    var dataobject = {
                        "tablename": tname,
                        "dbname": dbname,
                        "info": json_object,
                        "uname": uname
                    }

                    dataobject = $.toJSON(dataobject);

                    $.ajax({
                        type: "POST",
                        url: "insertIntoTable.php",
                        async: false,
                        data:"pInsertData=" + dataobject, 
                        success: function(msg){

                            console.log(msg);

                        }
                    });
                    //console.log(json_object);

                }

            }
        });
    });

    reader.readAsBinaryString(document.querySelector('input').files[0]);

The file is uploaded through an input in HTML. Thanks in Advance


Solution

  • Just pass default value in sheet_to_json method:

    var jsonObj = XLS.utils.sheet_to_json(data.Sheets[data.SheetNames[0]], {
                    header: 0,
                    defval: ""
                  });