Sheetjs: xlsx file corrupted after download with Angular2

Created on 4 Jul 2016  路  5Comments  路  Source: SheetJS/sheetjs

EDIT: for more details, see the angular 2+ demo

Hi,

I'm working with Angular 2 on frontend and Express on backend.

I've succeeded in creating a workbook with js-xlsx on backend.

var wopts = {showGridLines: false};

XLSX.writeFile(wb, 'output.xlsx', wopts);

res.status(201).send();

With code above, I could find the created file in backend folder and successfully open it.

Now I'd like to allow client side to download this file.
I modified my backend code as following :

var wopts = {
    bookType: 'xlsx',
    bookSST: false,
    type: 'buffer',
    showGridLines: false
};

var wbout = XLSX.write(wb, wopts);

res.end(wbout);

And on Angular 2 frontend, I have following code with FileSaver.js injected :

var headers = new Headers();

headers.append('Content-Type', 'application/json');

headers.append('responseType', 'arraybuffer');

this.authHttp.post('http://localhost:3001/createExcel', body, { headers: headers })
  .subscribe(
  response => {
    saveAs(new Blob([response._body], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }), "output.xlsx");
  },
  error => {
    alert(error.text());
    console.log(error.text());
  }
  );

Downloading is working well, but I can not manage to open it, with information :

We found a problem with some content in 'output.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.

Then

The file is corrupt and cannot be opened.

Any help will be appreciated, thanks!

Most helpful comment

I made it working by creating xlsx file with js-xlsx on client side and then directly download it, without any interaction with the server.

All 5 comments

I made it working by creating xlsx file with js-xlsx on client side and then directly download it, without any interaction with the server.

Could you please share your Angular 2 code. I am getting some really weird error when i try to write something on the file.

@zajjoseph Can you share your client side code for generating a xls file? Thanks.

@junaidinam @zh-wowtv
var saveAs = require('file-saver');
var wopts = { bookType: 'xlsx', bookSST: false, type: 'binary', showGridLines: false };

var wbout = XLSX.write(wb, wopts);

saveAs(new Blob([this.s2ab(wbout)], { type: '' }), 'test.xlsx');

s2ab(s: any) { var buf = new ArrayBuffer(s.length); var view = new Uint8Array(buf); for (var i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; return buf; }

Thanks @zajjoseph . It worked for me in angular 4.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jamesbillinger picture jamesbillinger  路  4Comments

sudhakar-sekar picture sudhakar-sekar  路  3Comments

Sankrish picture Sankrish  路  4Comments

goxr3plus picture goxr3plus  路  3Comments

happy0088 picture happy0088  路  3Comments