I have an angular 2 app where I am trying to parse an XLSX that is retrieved from http. I can't seem to get it to work. The logic does not fail/exception, but it only has a single sheet, and the sheet only has a couple columns that have really bad data in them. Here is the code I'm using:
this.http.get('assets/template.xlsx', {responseType: ResponseContentType.Blob})
.map((res) => res.blob())
.subscribe((data) => {
const wb: XLSX.WorkBook = XLSX.read(data, {type: 'buffer'});
const ws: XLSX.WorkSheet = wb.Sheets[wb.SheetNames[0]];
const json = XLSX.utils.sheet_to_json(ws, {header: 1});
console.log('test');
}, (err) => {
console.log(err);
});
I have tried various ResponseContentType values, and various read() "type" values, with no luck. Sometimes the combination I have tried just ends up freezing the browser.
Please advise how to do this...
Also, the XLXS I am trying to parse is more complicated. It has many styles, multiple sheets, some merged cells, etc. Will I run into any issues with this?
You have to generate a Uint8Array from the data. See the ajax example from https://github.com/sheetjs/js-xlsx#parsing-workbooks . The direct translation would be:
.subscribe((data) => {
const u8 = new Uint8Array(data);
const wb: XLSX.WorkBook = XLSX.read(u8, {type: 'array'});
Argument of type 'Blob' is not assignable to parameter of type 'ArrayBuffer'.
@seanmcilvenna You can convert the Blob to an ArrayBuffer by reading it with the FileReader. Inspired by https://stackoverflow.com/a/46568146/3472608:
const readBlob: XLSX.WorkBook = (blob: Blob) => new Promise((resolve) => {
const reader = new FileReader()
reader.onload = () => {
const array = new Uint8Array(reader.result)
resolve(XLSX.read(array, { type: 'array' }))
}
reader.readAsArrayBuffer(blob)
})
Most helpful comment
@seanmcilvenna You can convert the Blob to an ArrayBuffer by reading it with the FileReader. Inspired by https://stackoverflow.com/a/46568146/3472608: