Sheetjs: Parsing XLSX from angular 2 http

Created on 27 Oct 2017  路  3Comments  路  Source: SheetJS/sheetjs

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?

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:

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

All 3 comments

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)
})
Was this page helpful?
0 / 5 - 0 ratings

Related issues

jamespan0 picture jamespan0  路  3Comments

lxzhh picture lxzhh  路  3Comments

nishthasb picture nishthasb  路  4Comments

m-ketan picture m-ketan  路  3Comments

mmancosu picture mmancosu  路  3Comments