Angular6 读取XLS文件并保存到变量中

Angular 6 reading XLS file and saving it into a variable

我一直在尝试读取 XLS 文件并将其保存到局部变量中以便于使用,但我不断收到

TypeError: Cannot set property 'songs' of undefined

我从来没有尝试过读取 XLS,之前只有 csv,这要容易得多,但不幸的是这些文件无法转换。

这是当前使用的代码:

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);
    });
}

我也试过先将对象字符串化,但仍然会导致同样的错误。

我不确定它是否有效,但你可以试试这个:

添加这一行:

 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]);
 })

最终代码:

 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]);
 })

如果它不适合您,请提供一个 StackBlitz 示例!

我最终通过删除 forEach 循环解决了我的问题:

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

另一件有用的事情是在所述 forEach 循环之外创建一个临时变量,然后将 this.songs 分配给它。我不知道为什么这是我必须做的,但至少它有效而且我只需要第一个 sheet 所以。