Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send buffer data in express?

I am trying create and send an excel file to client. Client should download the file via ajax request, because I need filter parameters.

I am using excel4node package to create an excel file.

I write the code below and it's working for now but i am suspicious what if I will have data bigger than buffer. Is this the right way of using buffer? (please check the line with writeToBuffer method)

    const xl = require('excel4node');

    const excelCreator = function (data) {...}

    app.post('/api/excel', jsonParser, (req, res) => {

      let reqObj = {
        method: 'post',
        url: apiUrl + '/MemberService';,
        headers: {
          'Content-Type': 'application/json'
        },
        data: req.body
      };

      axios(reqObj)
        .then(response => {
          res.body = responseHandler(response); // a helper function to set res object

          let data = res.body.Data;

          res.setHeader('Content-Disposition', 'attachment; filename=' + 'excel.xlsx');
          res.type('application/octet-stream');
          res.body.Data = null;

          excelCreator(data).writeToBuffer().then(function (buffer) {
            res.body.Data = buffer;
            res.send(res.body);
          });

        })
        .catch(...);
    });
like image 795
Sam Avatar asked Jun 27 '18 12:06

Sam


1 Answers

First install SheetJS js-xlsx

npm --save install xlsx

Then you can send this response with Express:

const xlsx = require('xlsx')

var wb = xlsx.utils.book_new();

var table = [['a', 'b', 'c'], ['1', '2', '3']]
var ws = xlsx.utils.aoa_to_sheet(table);
xlsx.utils.book_append_sheet(wb, ws, 'test');

// write options
const wopts = { bookType: 'xlsx', bookSST: false, type: 'base64' };
const buffer = xlsx.write(wb, wopts);

res.writeHead(200, [['Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']]);
res.end(new Buffer(buffer, 'base64'));

Feel free to check the docs https://www.npmjs.com/package/xlsx

like image 155
vmf91 Avatar answered Nov 02 '22 19:11

vmf91