1

I have created an excel spreadsheet using the Excel4node library and then filled out this spreadsheet with the necessary data.

var excel = require('excel4node');
var workbook = new excel.Workbook();
var worksheet = workbook.addWorksheet('Sheet 1');

I then want the user to be able to download this spreadsheet and open it in Microsoft Excel.

workbook.write("Excel.xlsx", res);

This code works in the FireFox browser, however no download is prompted in Google Chrome or Microsoft Edge. Can anyone help me fix this issue? Any help would be much appreciated!

Alex Morrison
  • 186
  • 5
  • 18
  • use this instead of `workbook.write("Excel.xlsx", res);` ```wb.writeToBuffer().then(function(buffer) { res.send(buffer) });``` i havent tested but should work – bogdanoff Mar 15 '21 at 17:22
  • @Ajith-stark thanks for the reply. Just tested this in Edge and it successfully prompts the download. However it doesn't create the file as a spreadsheet. Also tested in Chrome and no download is prompted there. – Alex Morrison Mar 16 '21 at 09:09

1 Answers1

2

Forgot to set content-type header otherwise browser has to guess.

wb.writeToBuffer()
  .then(function(buffer) { 
   const filename = 'Testing workbook.xlsx'
    res
      .set('content-disposition', `attachment; filename="${filename}";  filename*=UTF-8''${encodeURI(filename)}`) // filename header
      .type('.xlsx') // setting content-type to xlsx. based on file extention
      .send(buffer) 
  });
Alex Morrison
  • 186
  • 5
  • 18
bogdanoff
  • 1,705
  • 1
  • 10
  • 20
  • This works perfectly in both Google Chrome and Mozilla FireFox now. But strangely in Microsoft Edge the user doesn't get the download prompt, any idea why that might be? – Alex Morrison Mar 18 '21 at 10:39
  • change `content-disposition` header line to this ```.set('content-disposition', `attachment; filename="${filename}"; filename*=UTF-8''${encodeURI(filename)}`)```. If this still does'nt work as expected, they dry downloading (export to .xlsx) some spreadsheet in `docs.google.com/spreadsheets`, if this also doesn't prompt download correctly then I don't know what to do. – bogdanoff Mar 19 '21 at 13:00
  • Yes thank you that works in all of those browsers now! – Alex Morrison Mar 19 '21 at 13:36