Prompt a csv file to download as pop up using node.js and node-csv-parser (node module)

后端 未结 5 1617
日久生厌
日久生厌 2020-12-23 18:15

Recently I have started working with node.js. While going through a requirement in one of my projects I am facing an issue where I should be able to write some data to a csv

5条回答
  •  借酒劲吻你
    2020-12-23 18:34

    Express-csv is a great module for writing csv contents to stream from a node.js server, which will be sent as a response to the client (and downloaded as a file). Very easy to use.

    app.get('/', function(req, res) {
      res.csv([
        ["a", "b", "c"]
      , ["d", "e", "f"]
      ]);
    });
    

    The docs: https://www.npmjs.com/package/express-csv

    When you pass an object, you need to prepend the headers explicitly (if you want them). Here's my my example using npm mysql

    router.route('/api/report')
        .get(function(req, res) {
                query = connection.query('select * from table where table_id=1;', function(err, rows, fields) {
                    if (err) {
                        res.send(err);
                    }
                    var headers = {};
                    for (key in rows[0]) {
                        headers[key] = key;
                    }
                    rows.unshift(headers);
                    res.csv(rows);
                });
        });
    

提交回复
热议问题