amedeiros
amedeiros

Reputation: 167

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.

Upvotes: 2

Views: 4383

Answers (2)

amedeiros
amedeiros

Reputation: 167

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.

Upvotes: 1

Prashant Pimpale
Prashant Pimpale

Reputation: 10717

I am not sure will it work or not but you can try this:

Add this line:

 var ref = this;

Before:

workbook.SheetNames.forEach(function (sheetName) {
 console.log(XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]));
 // add use ref.songs and then try
 ref.songs = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
 })

Final Code:

 var ref = this;

 workbook.SheetNames.forEach(function (sheetName) {
 console.log(XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]));
 // add use ref.songs and then try
 ref.songs = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
 })

If it is not working for you then please provide a StackBlitz Example!

Upvotes: 0

Related Questions