Accessing Cells with Sheetjs

Piter Parker picture Piter Parker · Feb 15, 2018 · Viewed 10.6k times · Source

I followed the demo here: https://github.com/SheetJS/js-xlsx/tree/master/demos/electron

I'm able to drag an excel file into my electron app.

The documentation says, you can access every cell with:

for(var R = range.s.r; R <= range.e.r; ++R) {
  for(var C = range.s.c; C <= range.e.c; ++C) {
    var cell_address = {c:C, r:R};
    /* if an A1-style address is needed, encode the address */
    var cell_ref = XLSX.utils.encode_cell(cell_address);
  }
}

How do I use it with my Code below? I got the content of the file stored in my test variable, but I'm not able to access it. The documentation lack of information there.

var do_file = (function() {
    return function do_file(files) {
        var f = files[0];
        var reader = new FileReader();
        reader.onload = function(e) {
            var data = e.target.result;
            data = new Uint8Array(data);
            test = XLSX.read(data, {type: 'array'});
            console.log(test);
        };
        reader.readAsArrayBuffer(f);
    };
})();

I got no clue how to start with it, thanks in advance

Answer

Piter Parker picture Piter Parker · Feb 16, 2018

Here it goes:

var do_file = (function() {
    return function do_file(files) {
        var f = files[0];
        var reader = new FileReader();
        reader.onload = function(e) {
            var data = e.target.result;
            data = new Uint8Array(data);
            //process_wb(XLSX.read(data, {type: 'array'}));
                        /* read the file */
            var workbook = XLSX.read(data, {type: 'array'}); // parse the file
            var sheet = workbook.Sheets[workbook.SheetNames[0]]; // get the first worksheet

            /* loop through every cell manually */
            var range = XLSX.utils.decode_range(sheet['!ref']); // get the range
            for(var R = range.s.r; R <= range.e.r; ++R) {
              for(var C = range.s.c; C <= range.e.c; ++C) {
                /* find the cell object */
                console.log('Row : ' + R);
                console.log('Column : ' + C);
                var cellref = XLSX.utils.encode_cell({c:C, r:R}); // construct A1 reference for cell
                if(!sheet[cellref]) continue; // if cell doesn't exist, move on
                var cell = sheet[cellref];
                console.log(cell.v);

        };
        reader.readAsArrayBuffer(f);
    };
})();