Skip to content

Instantly share code, notes, and snippets.

@mattn9x
Last active July 9, 2017 07:53
Show Gist options
  • Save mattn9x/874aeb613df5c171f7cd6780c75b709e to your computer and use it in GitHub Desktop.
Save mattn9x/874aeb613df5c171f7cd6780c75b709e to your computer and use it in GitHub Desktop.
config router export data
let express = require('express');
let router = express.Router();
let nodeXlsx = require('node-xlsx');
let User = require('./model/user.model');
let fs = require('fs');
/* GET home page. */
router.get('/', function (req, res) {
res.render('index', {title: 'Express'});
});
// Khi client truy cập router này thì server sẽ export ngay file excel xuống client
router.get('/export-download', function (req, res) {
let dataExcel = [];
User.find({})
.then(users => {
// Lay du lieu header cho file excel <=> lay cac key name trong collection
// O day cac key name cua collection user la: userName, email, phone
let arrHeaderTitle = [];
Object.keys(users[0]['_doc']).forEach(key => {
arrHeaderTitle.push(key);
});
dataExcel.push(arrHeaderTitle); // push header vao mang dataExcel
// Lay du lieu cac row tuong ung voi header <=> lay cac value tuong ung voi key name o tren
for (let item of users) {
let rowItemValue = [];
Object.keys(item._doc).forEach(key => {
rowItemValue.push(item[key]);
});
dataExcel.push(rowItemValue); // push tung dong value vao mang dataExcel
}
let buffer = nodeXlsx.build([{name: "List User", data: dataExcel}]); // Returns a buffer
res.attachment('users.xlsx');
res.send(buffer);
})
.catch(err => res.status(400).json(err));
});
module.exports = router;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment