xfscrypt
xfscrypt

Reputation: 286

Excel4Node: How to download an excel file without saving?

Using excel4node I am able to write the file to the harddrive. But rather I would like to return it as a download without saving the file on the server. I think the following code is required, but unsure how to use it:

wb.writeToBuffer().then(function(buffer) {
  console.log(buffer);
});

Does anyone have an idea on this?

Upvotes: 6

Views: 8906

Answers (4)

It's simple, you need to get the buffer values from wb.writeToBuffer(). it is in the format for JSZip.

Back-end:

let zip = new JSZip();
const XLSbuffer = await wb.writeToBuffer();
zip.file(`filename.xlsx`, XLSbuffer);
const content = await zip.generateAsync({ type: "base64" });
        
return res.status(200).send({XLSbuffer: content});

Front-end:

const download = function (data, namefile) {
        var byteCharacters = atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob([byteArray], { type: 'application/octet-stream' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.setAttribute('href', url);
        a.setAttribute('download', namefile);
        a.click();
    }
    
    const downloadReport = () => {        
        download(XLSbuffer, "report.zip");
    }

Upvotes: 0

teehid
teehid

Reputation: 9

//front-end react --

var fileDownload = require('js-file-download');  //npm i js-file-download
    axios({
        url:url,
        method: 'GET',
        responseType: 'blob', // Important
    }).then((response) => {
        fileDownload(response.data, `FileName.xlsx`);
    });

Upvotes: 0

Shubh Patel
Shubh Patel

Reputation: 61

Here is an example with nodeJS/Express GET Request. Is this what you're looking for ?

var xl = require('excel4node');

router.route("/test/").get((req, res) => {
    var wb = new xl.Workbook();
    var ws = wb.addWorksheet('SHEET_NAME');
    ws.cell(1, 1).string('ALL YOUR EXCEL SHEET FILE CONTENT');
    wb.write(`FileName.xlsx`, res);

});

Upvotes: 6

viveksharma
viveksharma

Reputation: 715

let binarybuffer = new Buffer(buffer, 'binary');
res.attachment('filename.xlsx'); 
return res.send(binarybuffer);

Upvotes: 2

Related Questions