typescriptjxls

Angular 6 reading XLS file and saving it into a variable


I've been trying to read a XLS file and save it into a local variable for ease of use but I am constantly getting

TypeError: Cannot set property 'songs' of undefined

I have never tried to read a XLS before only csv's which are a lot easier but unfortunately the files cant be converted.

This is the code that is currently being used:

public songs;

readFile(which_file: string) {
    this.actuallyReadFile().then((data) => {
        var workbook = XLSX.read(data, {
            type: 'binary'
        });

        workbook.SheetNames.forEach(function (sheetName) {
            console.log(XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]));
            this.songs = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
        })

    })
}

actuallyReadFile() {
    var reader = new FileReader();

    return new Promise((resolve, reject) => {
        reader.onload = function (e) {
            resolve(reader.result);
        };

        reader.onerror = function (ex) {
            console.log(ex);
        };

        reader.readAsBinaryString(this.file);
    });
}

I have also tried stringifying the object first but it still results in the same error.


Solution

  • I ended up solving my problem by removing the forEach loop:

    this.songs = <any>XLSX.utils.sheet_to_row_object_array(workbook.Sheets[workbook.SheetNames[0]]);
    

    Another thing that worked was making a temp variable out side of said forEach loop and then assigning this.songs to that instead. I don't know why this is what I had to do but at least it worked and I only need the first sheet so.