0
votes

Hi i'm new with nodeJs programming, in my project i need to read values from a xlsx file and i use SheetJs.

Now i'm trying to read a specific cell in the file following the online documentation. If i try to read the cell A1 from my file xlsx I have no errors, but if I try to read a different cell I get an error message. This is my code, taken from the documentation and in which I try to read cell C7 of the file, I can't understand why changing cell to read I get error.

CODE:

var XLSX = require('xlsx');

    /* data is a node Buffer that can be passed to XLSX.read */
    var workbook = XLSX.read('backend\Voti_Fantacalcio_Stagione_2020-21_Giornata_13.xlsx', {type:'buffer'});

    /* DO SOMETHING WITH workbook HERE */
    var first_sheet_name = workbook.SheetNames[0];
    console.log('Sheet name');
    console.log(first_sheet_name);
    console.log('End first_sheet_name');
    var address_of_cell = 'C7';
    var worksheet = workbook.Sheets[first_sheet_name];
    console.log('Worksheet start');
    console.log(worksheet);
    console.log('Worksheet end');
    var desired_cell = worksheet[address_of_cell];
    console.log('Inizio cella desiderata');
    console.log(desired_cell);
    console.log('Fine cella desiderata');
    var desired_value = (desired_cell ? desired_cell.v : undefined);
    console.log('Inizio valore cella desiderata');
    console.log(desired_value);
    console.log('Fine valore cella desiderata');

the xlsx file contains the votes of the fantasy football, and if you need to see how it is made it can be downloaded from this link (I do not know if I can post links, I apologize if I am wrong ): https://www.fantacalcio.it/voti-fantacalcio-serie-a

My console output:

Sheet name
Sheet1
End first_sheet_name
Worksheet start
{
  A1: {
    t: 's',
    v: 'backendVoti_Fantacalcio_Stagione_2020-21_Giornata_13.xlsx'
  },
  '!ref': 'A1'
}
Worksheet end
Inizio cella desiderata
undefined
Fine cella desiderata
Inizio valore cella desiderata
undefined
Fine valore cella desiderata
1

1 Answers

0
votes

Two issues:

  1. XLSX.read expects you to pass the contents of the file (your comment even says so, it's supposed to be a node buffer with the data in it). You are passing a file name though, so it's handles as if you had a CSV file containing one cell with the file name in it. Look at your A1! It's not even the right content. You need XLSX.readFile instead!

  2. You have a backslash in your path but you forgot to escape it (a backslash has a special meaning in a string literal). Add a second backslash in front.

So the fixed code is:

var workbook = XLSX.readFile('backend\\Voti_Fantacalcio_Stagione_2020-21_Giornata_13.xlsx')